-1

Ok so I need to make an object, modify its values using a Java scanner method, add it to a list, and do this 3 times so I have 3 objects in the list all with different values. I then need to use a for loop to print each object.

Here is my code so far. However every time the for loop outputs to to console, it prints 3 objects.. but their values are all the same (that of the final modification) For the sake of simplicity I won't add my class or method codes unless requested. So stuck on this!!

ArrayList<Car>carList = new ArrayList<Car>();

Car b = new Car(0, 0, 0, 0);

modifyCar(b);
carList.add(b);

modifyCar(b);
carList.add(b);

modifyCar(b);
carList.add(b);


for(Car x: carList)
{
   x.print();
}
tom
  • 45
  • 2
  • 10

1 Answers1

0

You're creating a single instance of Car, and then storing a REFERENCE to it in the List.

You then modify the instance, and store another reference to the SAME Car.

In the end, you'll end up with a list containing 3 references to the same Car, which will have the result of whatever modifyCar() does.

Create a new Car before calling modifyCar each time.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • Okay so what your saying is.. I'm going to have to have Car c = new Car() and Car d = new Car() in order for me to have 3 different objects in the list? – tom Aug 24 '18 at 04:02
  • No, you can reuse the b = new Car() if you like. – Will Hartung Aug 24 '18 at 04:38