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!
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.
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 ArrayList
s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With