两个新创建的对象似乎引用相同的地址 [英] Two newly created objects seem to refer to the same address

查看:88
本文介绍了两个新创建的对象似乎引用相同的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java编程只用了几个月,所以我不熟悉Java(有些技巧和我应该知道的基本知识)。

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?");
   }
}

这是我代码的摘录。

这怎么可能是真的?这是两个独立的对象。我不明白。

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

foo方法直接在我的main方法中调用(用于测试目的)。

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

如果你需要LabelText的构造函数,那么它是:

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;
    }
}


推荐答案

因为您正在将引用传递给数字而不进行复制,因此两个对象最终都指向相同的 int [] instance 。虽然有两个不同的外部对象,但它们都指向的内部对象是相同的对象,因此您可以通过取消引用<$ c $中的任何一个来更改该内部对象c> AText.numbers 和 BText.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.

您可以检查 AText == BText 将返回 false ,但 AText.numbers == BText.numbers 将返回 true 。并且 this.numbers == AText.numbers 也将返回 true

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
}

这篇关于两个新创建的对象似乎引用相同的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆