0

Let's say I have an Object called Index, this object has two attributes Long id; , String name; and I have two ArrayLists in my page, the problem is that when I edit the name of the index object in the first list it is being edited in the second list as well, here is my code to make the problem more understandable:

Index index1 = new Index();
index1.setName("1");
index1.setId(1);

List<Index> indexes = new ArrayList<Index>();
indexes.add(index1);

List<Index> newIndexes = new ArrayList<Index>();
newIndexes.add(index1);

Now if I update the name of the index in the indexes list it is being updated in the newIndexes list. note: the object index has equals method on the Id field.

Thanks

Shahe
  • 964
  • 2
  • 13
  • 34

4 Answers4

0

That is because index1 is just a reference to the object. So, your are basically adding the same reference to both of the lists. You need to copy the object before adding to the second list.

mcserep
  • 3,231
  • 21
  • 36
0

When you add the object to both the lists, the reference of that object is copied to the lists. And that's why when you object the object from one list, it is reflected back in the other. To avoid this, you need to create a copy of the object and add it to the other list, so that both do not refer to the same object.

Rahul
  • 44,383
  • 11
  • 84
  • 103
0

This is happening because when you use "Add" on array list (and in almost every data collection object) the collection is adding the "reference" of the object to its list, and not creating a new object. Thus, when both index1 objects at indexes and newIndexes are basically the same one. When changing it no matter where, it will be changed at the other as well.

Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0

The reference index1 is the same for both lists, so changing the Index referenced will change it in both.

Cloning the List per se won't fix your issue, as it'll clone the List but not its elements.

You need to perform a deep-clone of the List and its elements (or initialize a new ArrayList, as you do, and clone each of the previous List's elements) to solve your issue.

See here for the how-to.

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106