1

I have created new list from old list by using addAll() method, when i tried to modify new list, the old list is getting modified as well.

For Example -

List<A> list = new ArrayList<A>();
        list.add(new A("something1"));
        list.add(new A("something2"));
        list.add(new A("something3"));
        list.add(new A("something4"));
        List<A> newList = new ArrayList<A>();
        newList.addAll(list);
        for(A a1 : newList){
            a1.setA("something new");
        }

        System.out.println("list----------------");
        for(A a1 : list){
            System.out.println(a1.toString());
        }
        System.out.println("new list----------------");
        for(A a1 : newList){
            System.out.println(a1.toString());
        }

Output -

  list----------------
A [a=something new]
A [a=something new]
A [a=something new]
A [a=something new]
new list----------------
A [a=something new]
A [a=something new]
A [a=something new]
A [a=something new]

How to prevent this behavior and leave the old list as is ?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Derrick
  • 3,669
  • 5
  • 35
  • 50

2 Answers2

2

Java stores references to objects in a list. so if you make a copy list only the list object is different it still uses the same references to the A objects in other words the same A objects are in both lists. If you want to prevent this you will need to make clone copies of the A objects. The result would look like this:

List<A> newList = list.stream.map(a -> new A(a.getContent()).collect(Collectors.toList());

Or if you have a clone/copy method in A

List<A> newList = list.stream.map(A::clone).collect(Collectors.toList());
Dinomaster
  • 256
  • 1
  • 6
2

(The first version of your code has a typo. I'm assuming that doesn't exist in your real code.)

The real problem is that you are putting references to the same objects into two separate lists. When you call the set method, this is modifying the objects ... not the lists. Naturally, you can see the modifications to the objects via either list.

If you don't want that to happen, you will have to add copies of the objects in the first list to the second one. In order to do that, you need to implement a way to copy an instance of A. You could do this using:

  • a copy constructor,
  • a copy or clone method,
  • serialization and deserialization, or
  • ad hoc code.

Once you have a way to copy an A, you just iterate the first list adding copies of its entries to the second list.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216