尝试创建更多汽车实例,但是当我将它们添加到数组中时,它们将覆盖先前的实例,这是因为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",9 );
cars.autoArray.forEach(System.out::println);
}
}
最佳答案