如何从两个单独的类中将一个数组添加到另一个数组,然后从主类访问它? 总列表在打印时显示[],但第二类显示所有名称。
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);
}
}
答案 0 :(得分:1)
您的代码中缺少两个重要的行。
调用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);
}
}`
输出:
总列表为[约翰,法索,丽莎,迈克,兰迪,乔纳森] 第二类是[约翰,法索,丽莎,迈克,兰迪,乔纳森]