Two newly created objects seem to refer to the same address

  • A+

I'm programming in Java for only a few months so I'm not that experienced with Java (some tricks and the basic things I should know though).

I got a problem which may be obvious but I don't see it.

public class SomeClass {    private final int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};     private LabelText AText = new LabelText('A', numbers);    private LabelText BText = new LabelText('B', numbers);     public void foo() {        AText.numbers[6] = -1;        BText.numbers[3] = -1;        if (BText.numbers[6] == -1) System.out.println("Wtf?");    } } 

This is an extract from my code.

How this if can be true? These are two seperated objects. I don't get it.

The foo method is called directly in my main method (for test purposes).

If you need the constructor of LabelText, here it is:

public class LabelText {     private final char letter;    public int[] numbers;     public LabelText(char letter, int[] numbers) {        this.letter = letter;        this.numbers = numbers;     } } 


Because you are passing a reference to numbers without making a copy, so both objects end up pointing to the same int[] instance. While there are two different outer objects, the inner object that they both point to is the same object, hence you can change that inner object by dereferencing either of AText.numbers and BText.numbers, and the change will be visible in both of the outer objects when accessing their numbers fields.

You can check that AText == BText will return false, but AText.numbers == BText.numbers will return true. And this.numbers == AText.numbers will also return true.

Like try this same code but with this constructor:

public LabelText(char letter, int[] numbers) {    this.letter = letter;    this.numbers = numbers.clone(); // so it will always be unique array here } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: