Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign operator in Java

I have 2 ArrayLists in Java:

mProductList = new ArrayList<ProductSample>();
mProductList2 = new ArrayList<ProductSample>();

mProductList = productSampleList;

mProductList2 = productSampleList;

mProductList2 .remove(3);

The productSampleList has size 5. Why after this segment code is executed. mProductList has size 4?

Does we have any way to avoid this? I want the mProductList have size 5 as the same as productSampleList.
Thanks!

like image 392
Ngo Van Avatar asked Mar 13 '14 04:03

Ngo Van


2 Answers

Try this:

mProductList2 = new ArrayList<ProductSample>(productSampleList);

As it is currently, productSampleList, mProductList and mProductList2 all point to the same object, so changes to one will be reflected on the others. My solution was to simply create a copy of the list that can be modified independently of the original, but remember: productSampleList and mProductList are still pointing to the same object.

like image 151
Óscar López Avatar answered Nov 03 '22 08:11

Óscar López


All 3 productSampleList, mProductList and mProductList2 are references to the same ArrayList object, therefore calling the .remove() method on any one of them removes the element from the underlying single ArrayList object.

If you want to maintain separate ArrayList reference for each of your variables, you would need to create 3 different ArrayLists

like image 22
Alex Avatar answered Nov 03 '22 09:11

Alex