Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 can this be true? These are two separate 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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...