Java变量分配:为什么box1没有更新为box3?

时间:2019-04-04 16:54:12

标签: java variable-assignment pass-by-value

我有一个关于变量分配的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的引用更改为box3,它仍然指向box2。为什么会这样?

2 个答案:

答案 0 :(得分:9)

这是您的初始状态:

  //build a dictionary so you don't need to do n x m for loops
  var cDataDic = {};

  for(let i=0;i<cData.length;i++){
    if(cDataDic[cData[i].customer_name]){
        cDataDic[cData[i].customer_name].push(cData[i]);
    }else{
        cDataDic[cData[i].customer_name] = [cData[i]];
    }

  }


  //add lanes object
  for(let i=0;i<cData2.length;i++){
      if(cDataDic[cData2[i].customer]){
                cData2[i].lanes = cDataDic[cData2[i].customer]
      }
  }

这是 +-----------------+ +----------------+ | 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

现在,您应该能够弄清楚输出为何如此。 :)

答案 1 :(得分:0)

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

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”。这与复制引用的工作方式完全相同,并且始终具有相同的模式。