Java 更改引用但不更改对象本身? [英] Java changes reference but not the object itself?

查看:53
本文介绍了Java 更改引用但不更改对象本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码:

public static void main(String[] args)
{
    Test t1 = new Test();
    t1.i = 1;
    Test t0 = t1;
    Test t2 = new Test();
    t2.i = 2;
    t0 = t2; 
    System.out.println(t1.i); //prints 1, I thought it would print 2
}

在我通过简单的赋值从其他地方获取 t1 对象后,有没有办法更改它而不直接访问 t1?(即 t1 = t0)

Is there any way to change t1 object after I got it from somewhere else by simple assignment without accessing t1 directly? (i.e. t1 = t0)

推荐答案

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

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.

这篇关于Java 更改引用但不更改对象本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆