I have 2 arraylists.
List<MyObject> firstList (Size=5)
List<MyObject> secondList = firstList;
When I use this command
secondList.remove(0);
The object at 0 position in firstList is also getting deleted. What am I doing wrong here?
I have 2 arraylists.
List<MyObject> firstList (Size=5)
List<MyObject> secondList = firstList;
When I use this command
secondList.remove(0);
The object at 0 position in firstList is also getting deleted. What am I doing wrong here?
Only change the second line it will resolve your issue.
List<MyObject> firstList (Size=5)
List<MyObject> secondList = new ArrayList<>(firstList);
secondList.remove(0);
The issue is due to the your line List secondList = firstList;
It will not create another object instead of both the list point to the single object.
The problem is your line List<MyObject> secondList = firstList;
This doesnt create another list, it just refers to the first list you created. You'll need to instantiate a separate list.
Its correct because secondList
have the reference of firstList
so if you delete element form secondList
its same as removing from firstList
use following code:
//create new arraylist which contains item of firstList list
List<MyObject> secondList = new ArrayList(firstList);
secondList.remove(0);//now it will only remove element from `secondList`