1

I tried to construct list B from A in this way:

List<Integer> B = A;

However when I add a new item in B, A will also be modified. If I do it this way:

B.addAll(A);
B.add(new_element);

there is no previous problem.

Anyone know the reason why? Thanks a lot.

Superluffy
  • 11
  • 1

3 Answers3

6

Using = does not make a copy, it only points two variables at the same object.

Using one of the classic examples, if you have a class

class Foo {
  private List<Object> bar;

  constructor(List<Object> start) {
    bar = start;
  }

  getBar() {
    return this.bar;
  }
}

If you run:

List<Object> bar1 = new LinkedList<Object>();
Foo foo = new Foo(bar1);
bar1.getBar().add(new Object());

what would you expect the length of foo.getBar() to be?

Because you're only passing a reference to the list, rather than making a copy, the bar1.add call will actually add an item to foo's internal bar. They aren't separate lists, you've just told foo to hang on to a reference to bar1 and it will do so.

This means any change to the list will affect any other objects that may be holding a reference, which can be fatal when you have multi-threaded code or are passing someone data that you expect them not to change.

ssube
  • 47,010
  • 7
  • 103
  • 140
2

With that, you only copying the reference.

If you do A.add("Test"), then B will have also "Test" in it.

So if you use B in another part of your Java program and remove "Test", it will be also removed from A. But you will think that B is only modified, so you will have logical problems or side effects hard to debug.

JFPicard
  • 5,029
  • 3
  • 19
  • 43
0

So when you use '=', you just copy the reference of the main object. So if there are any changes in the main object then they will be reflected in another object too.

But when you use the addAll() method of the list, this function removes all the references to main objects and if you use the simple add() method it doesn't remove the references. So after adding a list using add(), if there are any changes in the added list then they will also reflected in the main list too. let's take the following example:

List<Object> l = new ArrayList<Object>();
List<Object> l1 = new ArrayList<Object>();
l1.add("Abhishek");

List<Object> l2 = new ArrayList<Object>();
l2.add("Vishvendra");

l.addAll(l1);
l.add(l2);

System.out.println(l.toString()); //this will print [Abhishek, [Vishvendra]]        

l1.add("Rushikesh");
l2.add("Talina");

System.out.println(l.toString()); //now this will print [Abhishek, [Vishvendra, Talina]]

I think that now it's quite easy to understand. check this for the behavior of addAll() method.

Rana
  • 150
  • 1
  • 12