How can i add one array to another from two separate classes, then access it from the main class? The total list shows [] when printed, but the second class shows all the names.
public class Main {
private static Plane fly = new Plane();
private static Secondclass sec = new Secondclass();
public static void main(String[] args) {
sec.addPassenger("John");
sec.addPassenger("Fatso");
sec.addPassenger("Lisa");
sec.addPassenger("Mike");
sec.addPassenger("Randy");
sec.addPassenger("Jonathan");
System.out.println("Total list is "+fly.getTotalList());
System.out.println("Second class is " + sec.getPassengerNames());
}
}
________________________________________
public class Plane {
private Secondclass sec;
private ArrayList<String> totalList;
public Plane() {
this.totalList = new ArrayList<String>();
}
public void addTotalList() {
this.totalList.addAll(sec.getPassengerNames());
}
public ArrayList<String> getTotalList() {
return totalList;
}
}
________________________________________
public class Secondclass{
private ArrayList<String> passengerNames;
public Secondclass() {
this.passengerNames = new ArrayList<String>();
}
public ArrayList<String> getPassengerNames() {
return passengerNames;
}
public void addPassenger(String name){
passengerNames.add(name);
}
}
Two important lines are missing in your code.
Call the plane.addTotalList()
import java.util.ArrayList; public class Main { private static Plane fly; private static Secondclass sec = new Secondclass(); public static void main(String[] args) { sec.addPassenger("John"); sec.addPassenger("Fatso"); sec.addPassenger("Lisa"); sec.addPassenger("Mike"); sec.addPassenger("Randy"); sec.addPassenger("Jonathan"); fly = new Plane(sec); fly.addTotalList(); System.out.println("Total list is " + fly.getTotalList()); System.out.println("Second class is " + sec.getPassengerNames()); } } class Plane { private Secondclass sec; private ArrayList<String> totalList; public Plane(Secondclass sec) { this.sec = sec; this.totalList = new ArrayList<String>(); } public void addTotalList() { this.totalList.addAll(sec.getPassengerNames()); } public ArrayList<String> getTotalList() { return totalList; } } class Secondclass { private ArrayList<String> passengerNames; public Secondclass() { this.passengerNames = new ArrayList<String>(); } public ArrayList<String> getPassengerNames() { return passengerNames; } public void addPassenger(String name) { passengerNames.add(name); } }`
The output:
Total list is [John, Fatso, Lisa, Mike, Randy, Jonathan] Second class is [John, Fatso, Lisa, Mike, Randy, Jonathan]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.