-1

I have an ArrayList in which I am adding some items.

    private List<Product> mMainList = new ArrayList<>();
    private List<Product> mCopyList;

    mMainList.add(new Product(true,"First"));
    mMainList.add(new Product(true,"Second"));
    mMainList.add(new Product(true,"Third"));

Now I have a new list mCopyList to which I am initialising with mMainList

mCopyList = new ArrayList<>(mMainList);

Now I am changing the name of a product of 0th index in mCopyList

mCopyList.get(0).setName("First After Change");

Problem

The problem I am facing is, mMainList is getting changed automatically. I don't want to change mMainList. Please suggest. Thank You.

Ashish Tiwari
  • 2,168
  • 4
  • 30
  • 54
  • You copy the List right, but the reference to the elements is the same. So you have to do a deep copy. – Jens May 18 '18 at 06:50
  • While adding data into `mCopyList ` using object cloning technique, means by set data by using `getter()` and `setter()` and then add your data into `mCopyList `. By using this technique you will not face this issue. – Swapnil Kshirsagar May 18 '18 at 06:54
  • @SwapnilKshirsagar it doesn't work. I tried ` mCopyList = new ArrayList<>(mMainList); Product product = mCopyList.get(0); product.setName("First After Change"); product.setActive(false);` – Ashish Tiwari May 18 '18 at 07:20
  • @AshishTiwari An example is in the link to the duplicate – Jens May 18 '18 at 07:30
  • @Jens got it. thank you. I was thinking addAll() and new operator can do this. – Ashish Tiwari May 18 '18 at 08:16

1 Answers1

0

Try to clone of main arraylist like this

private List<Product> mMainList = new ArrayList<>();
    private List<Product> mCopyList;

    mMainList.add(new Product(true,"First"));
    mMainList.add(new Product(true,"Second"));
    mMainList.add(new Product(true,"Third"));

now clone of arraylist

mCopyList= (ArrayList<>)mMainList.clone();

now change is clone list

mCopyList.get(0).setName("First After Change");

this will not affect your main list. hope it will help you!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
  • 1
    Thanks Hemant. but it says "clone has protected access in java.lang.Object – Ashish Tiwari May 18 '18 at 07:07
  • hello @Hemant Parmar can you help me with this https://stackoverflow.com/questions/49952965/recyclerview-horizontal-scrolling-to-left?rq=1 –  May 18 '18 at 07:08
  • Try this when you change the value of mCopyList: mCopyList.set(0,"First After Change"); This would not change the value of mMainList. – besartm May 18 '18 at 07:15