为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

杨魅力 2022-09-01 18:00:01
尝试创建更多的汽车实例,但是当我将它们添加到数组中时,它们将覆盖以前的实例,这是因为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);}}
查看完整描述

3 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

您需要创建一个新的 in,而不是修改现有的 :AutomobileaddVehicle()


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

    autoArray.add(new Automobile(m, c, y, mile));

    return autoArray;

}

这应该可以解决您的问题。但是,是的,理想情况下,您还应该像其他注释者建议的那样重构代码,因为在 的每个实例中创建一个 没有意义。ArrayList<Automobile>Automobile


查看完整回答
反对 回复 2022-09-01
?
PIPIONE

TA贡献1829条经验 获得超9个赞

试着更具体地思考你的情况。假设您的类表示一个实际的、真实的汽车世界。Automobile


对于一个人来说,有一个其他汽车的列表有意义吗?您的现实世界汽车是否包含其他汽车?Automobile


这里更好的方法是从类中完全删除 。相反,该列表应保留在您向其添加新汽车的其他地方。ArrayListAutomobile


以下是一种可能的新方法供您考虑:main()


public static void main(String[] args) {


    ArrayList<Automobile> autos = new ArrayList<>();

    autos.add(new Automobile("kelvin", "luke", 6, 9));

    autos.add(new Automobile("horny", "luke", 6, 9));


    autos.forEach(System.out::println);

}


查看完整回答
反对 回复 2022-09-01
?
侃侃无极

TA贡献2051条经验 获得超10个赞

您的问题在于对象的存储方式。通过更改 Automobile 类的参数,然后添加到列表中,您只需使用已编辑的参数再次添加同一实例。this

您需要将 List 移到 Automobile 类之外,然后使用构造函数创建新的 Automobiles,然后将它们添加到列表中。


查看完整回答
反对 回复 2022-09-01
  • 3 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号