Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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

When you are using list, (or arraylist) the size() method returns the number of elements in the list. lists are not like arrays, where the size is fixed. If you want a fixed size, use arrays.

Have a look at http://docs.oracle.com/javase/7/docs/api/java/util/List.html to learn more about lists.

Here is a good distinction between arrays and arraylists.

You can try this:-

    public class ArrayListTest {

    public static void main(String str[]){
        ArrayList productSampleList=new ArrayList();
        ArrayList mProductList=null;
        ArrayList mProductList2=null;

        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");

        System.out.println("Main productSampleList size..."+productSampleList.size());
        mProductList=new ArrayList(productSampleList);
        mProductList2=new ArrayList(productSampleList);
        System.out.println("mProductList size..."+mProductList.size());
        System.out.println("mProductList2 size..."+mProductList2.size());
        mProductList2.remove(1);
        System.out.println("mProductList size..."+mProductList.size());
        System.out.println("mProductList2 size..."+mProductList2.size());

    }
}

Output:-

Main productSampleList size...5

mProductList size...5

mProductList2 size...5

mProductList size...5

mProductList2 size...4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top