I have few object say: Car, Auto and AutoCar
Car
- String name;
- String origin;
Auto
- String type;
AutoCar
- String type;
- List<Car> cars = new ArrayList<Car>();
Iterating for list of autos:
List<Car> carList = //fetched from a service or method
List<AutoCar> acList = new ArrayList<AutoCar>();
for(Auto auto : autos){
AutoCar ac = new AutoCar();
ac.setType(auto.getType());
ac.setCars(carList);
acList.add(ac);
}
I would expect result:
Type = CAR-Type-1
Cars:
name: FORD
origin: US
name: Suzuki
origin: Japan
Type = CAR-Type-2
Cars:
name: Volkswagen
origin: Germany
name: Audi
origin: Germany
Type = CAR-Type-3
Cars:
name: Jaguar
origin: UK
name: Ferrari
origin: Italy
But what I get is the last iteration preserved...
Cars:
name: Jaguar
origin: UK
name: Ferrari
origin: Italy
for all car Types (CAR-Type-1/CAR-Type-2/CAR-Type-3)
I think I am doing it wrong at this line:
ac.setCars(carList);
Please let me know if I am not clear.
carListcorrectly filled before you enter this loop? Are you updating it anywhere else? Can you check the value before it enters the loop?carListin each iteration of your loop; otherwise, you are setting the same list in all AutoCars