gpt4 book ai didi

Java变量赋值: why is box1 not updated to box3?

转载 作者:行者123 更新时间:2023-12-03 20:20:56 24 4
gpt4 key购买 nike

我有一个关于变量赋值的 java 基础知识的初学者问题。

在我的示例代码中,我有 3 个框(对象)。我按如下方式分配框:

    Box box1 = new Box("Furniture", 1);
Box box2 = new Box("Games", 2);
Box box3 = new Box("Cloths", 3);

box1 = box2;
box2 = box3;

System.out.println(box1.toString());
System.out.println(box2.toString());

现在,我希望 box1 也指向 box3。但事实证明,它仍然指向 box2,尽管我也将 box2 的引用更改为 box3。为什么会这样?

最佳答案

这是你的初始状态:

     +-----------------+             +----------------+
| box1 ( ref ) +------------>| box1 ( obj ) |
+-----------------+ +----------------+

+-----------------+ +----------------+
| box2 ( ref ) +------------>| box2 ( obj ) |
+-----------------+ +----------------+

+------------------+ +----------------+
| box3 ( ref ) +----------->| box3 ( obj ) |
+------------------+ +----------------+

这是 box1 = box2 之后发生的事情:

     +-----------------+             +----------------+
| box1 ( ref ) +----+ | box1 ( obj ) |
+-----------------+ | +----------------+
|
+-----------------+ +------> +----------------+
| box2 ( ref ) +------------>| box2 ( obj ) |
+-----------------+ +----------------+

+------------------+ +----------------+
| box3 ( ref ) +----------->| box3 ( obj ) |
+------------------+ +----------------+

这是 box2 = box3 之后发生的事情

     +-----------------+             +----------------+
| box1 ( ref ) +----+ | box1 ( obj ) |
+-----------------+ | +----------------+
|
+-----------------+ +------> +----------------+
| box2 ( ref ) +----+ | box2 ( obj ) |
+-----------------+ | +----------------+
|
+------------------+ +------->+----------------+
| box3 ( ref ) +----------->| box3 ( obj ) |
+------------------+ +----------------+

现在您应该能够弄清楚为什么输出是这样的。 :)

关于Java变量赋值: why is box1 not updated to box3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521284/

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