-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
  • 37,241
  • 25
  • 195
  • 267
Anirudh
  • 2,767
  • 5
  • 69
  • 119

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,709
  • 4
  • 42
  • 59
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
  • 15,743
  • 6
  • 59
  • 89