-3

I'm adding items to a List but the previous item always gets overwritten by later after the iteration.

List<CartPojo> cartLists = new ArrayList<CartPojo>();
CartPojo cartItem = new CartPojo();

for(int k=0; k<2; k++){
   cartItem.setItemName("name_"+k);
   cartLists.add(cartItem);
}

model.addAttribute("cartLists", cartLists);

This gives the output: name_1, name_1

Expected output: name_0, name_1

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
irengba
  • 37
  • 2
  • 4
  • 3
    You're always adding the same object. Put CartPojo cartItem = new CartPojo(); into the for loop. –  Jun 11 '17 at 16:43
  • Create the new item inside the loop, not outside. Otherwise you're just adding the same item over and over. – Lew Bloch Jun 11 '17 at 16:43
  • You can get more examples here: https://stackoverflow.com/questions/44486240/add-items-to-list-in-java and https://stackoverflow.com/questions/2697182/how-to-use-an-array-list – Vasyl Lyashkevych Jun 11 '17 at 16:44

6 Answers6

1

Currently, you're operating on the same instance throughout the iterations, rather you should instantiate the object inside the loop i.e:

for(int k=0; k<2; k++){
   CartPojo cartItem = new CartPojo();
   cartItem.setItemName("name_"+k);
   cartLists.add(cartItem);
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You are keep modifying the same object each time. You need to create Object inside the loop.

for(int k=0; k<2; k++){
   CartPojo cartItem = new CartPojo();
   cartItem.setItemName("name_"+k);
   cartLists.add(cartItem);
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You are not declaring new "CartPojo" instances, so every time you do something on cartItem, it is the same object every time that is being manipulated.

Meccano
  • 537
  • 4
  • 8
0

Just put Cartpojo cartItem=new CartPojo(); inside the for loop

List cartLists = new ArrayList();

for(int k=0; k<2; k++){

CartPojo cartItem = new CartPojo();

cartItem.setItemName("name_"+k);

cartLists.add(cartItem);

}

Shaine
  • 80
  • 1
  • 10
0

You just need to create object every time inside the loop

List<CartPojo> cartLists = new ArrayList<CartPojo>();


for(int k=0; k<2; k++){
   CartPojo cartItem = new CartPojo();
   cartItem.setItemName("name_"+k);
   cartLists.add(cartItem);
}

model.addAttribute("cartLists", cartLists);

Peace

Anand Siddharth
  • 967
  • 1
  • 9
  • 30
0

You use the same object in all iterations. You should create an instance (with the new operator) at each time you want to create a CartPojo object.

Besides you should provide a constructor in CartPojo :

for(int k=0; k<2; k++){
    CartPojo cartItem = new CartPojo("name_"+k);
    cartLists.add(cartItem);
}

It makes the code more clear.

davidxxx
  • 125,838
  • 23
  • 214
  • 215