gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:06:00 24 4
gpt4 key购买 nike

尝试创建更多的汽车实例,但是当我将它们添加到数组时,它们会覆盖之前的实例,这是因为 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);
}

最佳答案

您需要创建一个新的 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 的每个实例中.

关于java - 如何在不覆盖以前的副本的情况下将对象添加到类中的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55330616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com