gpt4 book ai didi

java - 为什么对象 "person1"和对象 "person2"是相同的?

转载 作者:行者123 更新时间:2023-12-02 07:33:01 24 4
gpt4 key购买 nike

在此程序中,每当您更改 person1 或 person 3 时,它们都会包含相同的值。我尝试用伪代码完成每个步骤,但我迷失了这两个对象始终相等背后的推理。您能帮忙解释一下这些步骤吗?我真的很想了解。感谢您抽出时间。

public class References1
{
public static void main (String[] args)
{
Person person1 = new Person ("Rachel", 6);
Person person2 = new Person ("Elly", 4);
Person person3 = new Person ("Sarah", 19);

System.out.println ("\nThe three original people...");
System.out.println (person1 + ", " + person2 + ", " + person3);

// Reassign people
person1 = person2;
person2 = person3;
person3 = person1;


System.out.println("\nThe three people reassigned...");
System.out.println (person1 + ", " + person2 + ", " + person3);

System.out.println();
System.out.println ("Changing the second name to Bozo...");
person2.changeName ("Bozo");
System.out.println (person1 + ", " + person2 + ", " + person3);

System.out.println();
System.out.println ("Changing the third name to Clarabelle...");

person3.changeName ("Clarabelle");
System.out.println (person1 + ", " + person2 + ", " + person3);
System.out.println();
System.out.println ("Changing the first name to Harpo...");
person1.changeName("Harpo");
System.out.println (person1 + ", " + person2 + ", " + person3);
}
}

最佳答案

这些是导致您的问题的行:

// Reassign people
person1 = person2;
person2 = person3;
person3 = person1;

如果变量具有以下起始值:

person1 = "A";
person2 = "B";
person3 = "C";

...然后你通过代码运行它:

person1 = person2 -> person1 is now set to "B" (the value "A" is discarded)

person2 = person3 -> person2 is now set to "C"

person3 = person1 -> person3 is now set to the value of person1 which is "B"

现在变量 person1 和 person3 设置为同一个对象。

关于java - 为什么对象 "person1"和对象 "person2"是相同的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26856748/

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