For last few days I was trying figure out how to make linkedList as class field works. In my project, I am creating object and than after few irations i would like to set field with linkedList. I have made simple model of this problem below. First we are creating new "Car", than we are seting ArrayList (same problem with linkedlIst), than we are addin to list of cars. During this everyting is ok. Object gets this list and its seeing inside. But when I will add more objects to the list or just generate another LinkedList(Classfield for another object), all object will get new field like that last one. Exaple below:
public static void main(String[] args) {
ArrayList<LinkedList> colors = new ArrayList();
LinkedList<LinkedList> opcje = new LinkedList();
List<Car> cars = new ArrayList<>();
Car car1 = new Car("Ford1");
colors.add(generateColors(car1));
car1.setColors(colors);
cars.add(car1);
colors.clear();
Car car2 = new Car("Ford2");
colors.add(generateColors(car2));
car2.setColors(colors);
cars.add(car2);
colors.clear();
Car car3 = new Car("Ford3");
colors.add(generateColors(car3));
car3.setColors(colors);
cars.add(car3);
System.out.println(car1.getColors().toString());
System.out.println(car1.getColors());
for(Car c : cars) {
System.out.println(c.toString());
}
System.out.println(car1.getColors().toString());
}
and Car.class
public class Car {
private String name;
private String engine;
private ArrayList<LinkedList> colors;
public Car(String name) {
this.name=name;
}
public ArrayList<LinkedList> getColors() {
return colors;
}
public void setColors(ArrayList<LinkedList> colors) {
System.out.println("Setting up colors for "+colors.toString());
this.colors = colors;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "name : "+name+" colors: "+colors.toString();
}
}
The result of this will be:
name : Ford1 colors: [[Ford3]]
name : Ford2 colors: [[Ford3]]
name : Ford3 colors: [[Ford3]]
What am I doing wrong?