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.