Assigning operators in Java
•
Java
I have two ArrayLists in Java:
mProductList = new ArrayList<ProductSample>(); mProductList2 = new ArrayList<ProductSample>(); mProductList = productSampleList; mProductList2 = productSampleList; mProductList2 .remove(3);
The size of the productsamplelist is 5 Why after executing this code The size of the mproductlist is 4?
Is there any way we can avoid this? I want the size of the mproductlist to be 5, the same as the productsamplelist thank you!
Solution
Try this:
mProductList2 = new ArrayList<ProductSample>(productSampleList);
As at present, productsamplelist, mproductlist and mproductlist2 all point to the same object, so changes to other objects will be reflected on other objects My solution is to simply create a copy of the list that can be modified independently of the original file, but remember: productsamplelist and mproductlist still point to the same object
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码