Java变量赋值:为什么box1没有更新到box3?

Java variable assignment: why is box1 not updated to box3?

我有一个关于 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。为什么会这样?

看看以下内容是否对您更有意义。

int box1 = 1;
int box2 = 2;
int box3 = 3;

box1 = box2;
box2 = box3;

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

box1 打印“2”,box2 打印“3”。这与复制引用的工作方式完全相同,并且它始终具有相同的模式。

这是您的初始状态:

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

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