gpt4 book ai didi

java - 有人可以解释一下Java中的对象引用吗?

转载 作者:行者123 更新时间:2023-12-01 13:58:43 25 4
gpt4 key购买 nike

我得到的输出是 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);
}
}

最佳答案

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

关于java - 有人可以解释一下Java中的对象引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19478122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com