-3

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?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Anirudh
  • 2,457
  • 4
  • 54
  • 100

3 Answers3

5

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.

Maheshwar Ligade
  • 6,507
  • 4
  • 40
  • 58
0

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.

Nick Badal
  • 681
  • 1
  • 8
  • 26
0

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`
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100