且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 更改引用但不更改对象本身?

更新时间:2022-05-11 01:39:23

这是您的程序及其功能的说明.系统的每个状态用虚线分隔.

Here is an illustration of your program and what it does. Each state of the system is shown separated by a dashed line.

注意当你执行 t0 = t1 时会发生什么.您认为这意味着从现在开始,t0t1 是同义词 - 无论何时使用一个,另一个都会受到影响.但实际上,t0t1 只是对同一个对象的两个引用.

Note what happens when you do t0 = t1. You assumed that this means that from now on, t0 and t1 are synonyms - whenever you use one, the other is affected. But in fact, t0 and t1 are simply two references to the same object.

t0 进行新的赋值只是将它从蓝色"对象中分离出来,然后将其重新附加到紫色"对象上.

Making a new assignment to t0 simply detached it from the "blue" object and re-attached it to the "violet" object.

只要 t0t1 都指向同一个对象,您对其所指向对象的内容所做的任何更改(例如 t0.i = 5) 会被另一个引用看到,因为它们都指向同一个对象.但是,一旦您将其他内容分配给 t0,它就会失去与 t1 的连接.完成后,更改将反映在 t2 中,它指向相同的紫罗兰色"对象,而不是 t1 中仍指向旧的蓝色"对象"一个.

As long as t0 and t1 were both pointing at the same object, any changes you make in the content of their pointed object (such as t0.i = 5) would be seen by the other reference, because they both refer to the same object. But as soon as you assign something else to t0, it loses its connection to t1. After you do that, changing it will be reflected in t2, which points to the same, "violet" object, not in t1 which still points to the old, "blue" one.

所以:

  • 如果您为引用分配一个新值 - 它不再像以前一样指向同一个对象,并且之前的任何双重引用"都将丢失.
  • 如果您为引用的内容分配一个新值,它将反映在所有查看同一对象的引用变量中.
  • If you assign a new value to the reference - it no longer points to the same object as before, and any previous "double referencing" is lost.
  • If you assign a new value to the content of the reference, it will be reflected in all reference variables that look at the same object.