如何在不覆盖以前的副本的类中将对象添加到 ArrayList 中

尝试创建更多的汽车实例,但是当我将它们添加到数组中时,它们将覆盖以前的实例,这是因为ArrayList位于我创建的每个实例中,因此创建一个具有ArrayList来保存所有内容的清单类会更好吗?


import java.util.ArrayList;


public class Automobile {


private String make;

private String color;

private int year;

private int mileage;

private ArrayList<Automobile> autoArray = new ArrayList<>();


public Automobile(String make, String color, int year, int mileage) {

    this.make = make;

    this.color = color;

    this.year = year;

    this.mileage = mileage;

    autoArray.add(this);



}


//setters (mutators)

public void setYearModel(int y) {

    year = y;

}


public void setMake(String type) {

    make = type;

}


public void setColor(String col) {

    color = col;

}


public void setMileage(int miles) {

    mileage = miles;

}


public String toString() {

    return "test = " + color + "; test " + year + "; test " + year + "; test " + make;

}



private ArrayList addVehicle(String m, String c, int y, int mile) {

    this.make = m;

    this.color = c;

    this.year = y;

    this.mileage = mile;

    autoArray.add(this);

    return autoArray;

 }

    public static void main(String[] args) {


    Automobile cars = new Automobile("kelvin","luke", 6, 9 );

    cars.autoArray.forEach(System.out::println);

    cars.addVehicle("horny","luke", 6, 9 );

    cars.autoArray.forEach(System.out::println);

}

}


杨魅力
浏览 94回答 3
3回答

慕沐林林

您需要创建一个新的 in,而不是修改现有的 :AutomobileaddVehicle()private ArrayList addVehicle(String m, String c, int y, int mile) {&nbsp; &nbsp; autoArray.add(new Automobile(m, c, y, mile));&nbsp; &nbsp; return autoArray;}这应该可以解决您的问题。但是,是的,理想情况下,您还应该像其他注释者建议的那样重构代码,因为在 的每个实例中创建一个 没有意义。ArrayList<Automobile>Automobile

PIPIONE

试着更具体地思考你的情况。假设您的类表示一个实际的、真实的汽车世界。Automobile对于一个人来说,有一个其他汽车的列表有意义吗?您的现实世界汽车是否包含其他汽车?Automobile这里更好的方法是从类中完全删除 。相反,该列表应保留在您向其添加新汽车的其他地方。ArrayListAutomobile以下是一种可能的新方法供您考虑:main()public static void main(String[] args) {&nbsp; &nbsp; ArrayList<Automobile> autos = new ArrayList<>();&nbsp; &nbsp; autos.add(new Automobile("kelvin", "luke", 6, 9));&nbsp; &nbsp; autos.add(new Automobile("horny", "luke", 6, 9));&nbsp; &nbsp; autos.forEach(System.out::println);}

侃侃无极

您的问题在于对象的存储方式。通过更改 Automobile 类的参数,然后添加到列表中,您只需使用已编辑的参数再次添加同一实例。this您需要将 List 移到 Automobile 类之外,然后使用构造函数创建新的 Automobiles,然后将它们添加到列表中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java