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

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);
}

TA贡献2051条经验 获得超10个赞
您的问题在于对象的存储方式。通过更改 Automobile 类的参数,然后添加到列表中,您只需使用已编辑的参数再次添加同一实例。this
您需要将 List 移到 Automobile 类之外,然后使用构造函数创建新的 Automobiles,然后将它们添加到列表中。
添加回答
举报