0

I am new to java and I'm trying to take some exams to test my knowledge. One particular question kind of gotten under my skin (lol).

List<String> x = new ArrayList<String>();

x.add("A");
x.add("B");

List<String> y = x;
y.add("C");

System.out.println(x);
System.out.println(y);

The output I would have expected is

[A, B]
[A, B, C]

But apparently, whatever you do with Y will also happen to X. Both of them have this value now:

[A, B, C]

My first question is why? Would you happen to know any reference that I can study as to when to expect this to happen in a Java object?

christianleroy
  • 1,084
  • 5
  • 25
  • 39
  • 2
    There is no copy when you say `List y = x;`. `y` and `x` **point** to the same `List`. For the behavior you expected, you'd need `List y = new ArrayList<>(x);` – Elliott Frisch Sep 07 '16 at 01:52
  • @ElliottFrisch When can I expect that when I assign an Object X to Object Y, that the Object Y would just be a reference to Object X, instead of a new Object with the same value? – christianleroy Sep 07 '16 at 02:07
  • 2
    When you don't have a `new`, it's going to be the same `Object` reference. – Elliott Frisch Sep 07 '16 at 02:07
  • If it looks like `x=y`, then it's _always_ going to be a reference to the same object. But then if you later do `y = somethingElse()`, then the reference changes again and `x` doesn't change. – Louis Wasserman Sep 07 '16 at 04:48

0 Answers0