0

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.

3
  • I don't think there is enough info here. Is carList correctly filled before you enter this loop? Are you updating it anywhere else? Can you check the value before it enters the loop? Commented Apr 24, 2015 at 12:45
  • do you want to get all cars of same type? or do I get you wrong? Commented Apr 24, 2015 at 12:46
  • You should get a new carList in each iteration of your loop; otherwise, you are setting the same list in all AutoCars Commented Apr 24, 2015 at 12:48

3 Answers 3

1

You need to create a new carList for each auto, if you reuse the same every auto is going to have the same list of cars.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to fill carList for every auto. That means your service/method needs to accept a type parameter that returns all Car objects for that type, and you have to call it from within your loop over autos.

for (Auto auto : autos) {
  AutoCar ac = new AutoCar();
  ac.setType(auto.getType());
  ac.setCars(carService.getCarsByType(auto.getType())); //<-- your service/method call here
  acList.add(ac);
}

2 Comments

I accept this Answer. But I am actually struck on iterating and using the object in Hibernate which is more of a transnational issue I will have to resolve. Thanks.
That is different from what you initially asked, maybe you should ask it in a new question.
0

You are fetching carList only once and setting the same carList in the iterations. Fetch carList according to car type every time then set it accordingly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.