0

我得到的输出是 9 12 1 11 12 但它应该是 9 9 1 12 12。我知道它与 a2 = a1; 但看不到如何。

public class C {

   /**
    * @param args the command line arguments
    */ 
    private int i;
    private int k = 10;

    public static void main(String[] args) {
    // TODO code application logic here

       C a2 = new C();
       C a1 = new C();
       C a3 = new C();

       a1.i = a3.i;
       a2 = a1; 
       a2.i = 12;
       a3.i = a3.i + 1;
       a1.i = 9;
       a1.k = 11;
       a2.k = 12;
       System.out.println(a1.i + " " + a2.i + " " + a3.i + " " + a1.k + " " + a2.k);
    }
}
4

3 回答 3

1
C a2 = new C();
C a1 = new C();
C a3 = new C();

a1.i = a3.i; // => a3.i = 0 then a1.i = 0;
a2 = a1; // => a1 and a2 are the same objects (point to the same references)
a2.i = 12; //=> a2.i = 12, so a1.i = 12
a3.i = a3.i + 1;// => a3.i = 1
a1.i = 9; // => a1.i = 9 so a2.i = 9
a1.k = 11; // => a1.k = 11 so a2.k = 11
a2.k = 12; // => a2.k = 12 so a1.k = 12
//a1.i = 9 / a2.i = 9 / a3.i = 1 / a1.k = 12 / a2.k = 12
System.out.println(a1.i + " " + a2.i + " " + a3.i + " " + a1.k + " " + a2.k);
于 2013-10-20T13:57:03.633 回答
0

此代码:a2=a1表示引用a2将指向与 相同的对象a1

因此,您有 2 个指向同一个对象的引用。当对象更改时,如果您使用任一引用,您将获得相同的值。

还。通过运行你的程序,我得到了正确的值:9 9 1 12 12

于 2013-10-20T13:57:47.553 回答
0

也许一些评论会帮助你理解发生了什么:

a1.i = a3.i; // a3.i = 0 = a1.i
a2 = a1;  // now the old object a2 is lost and a2 points to a1
a2.i = 12; // a2.i = 12 = a1.i
a3.i = a3.i + 1; // a3.1 = 0 + 1
a1.i = 9; // a1.i = 9 = a2.i
a1.k = 11; // a1.k = 11 = a2.k
a2.k = 12; // a2.k = 12 = a1.k

在执行结束时,我们有:

a1.i = 9
a2.i = 9
a3.i = 1
a1.k = 12
a2.k = 12
于 2013-10-20T13:59:54.613 回答