Java中的对象分配 [英] Object assignment in java

查看:104
本文介绍了Java中的对象分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个班级考试.
测试t1 = new Test();
测试t2 = new Test();
t2 = t1;
我知道t1的任何变化都会影响t2.请告诉我原因是什么?

Hi all,

I have a class Test.
Test t1 = new Test();
Test t2 = new Test();
t2 = t1;
I know any change in t1 will affect t2. Please tell me what is the reason for that?

推荐答案

原因很简单:在t2 = t1之后,两个变量都引用了同一类的一个实例.测试.创建并分配给t2的对象不再在任何地方引用,并且可以进行垃圾回收.

干杯!

--MRB
The reason is quite simple: After t2=t1 both variables hold a reference to one and the same instance of class Test. The object created and assigned to t2 is no longer referenced anywhere and can garbage collected.

Cheers!

--MRB


分配前
t1 -----> Memory for t1
t2 -----> Memory for t2



将t1分配给t2时,t1的引用将传递给t2.



When you assign t1 to t2, reference of t1 is passed to t2.

t1 -----> Memory for t1
t2 ---|



因此,两个变量都指向同一对象.
对它们中的任何一个的更改都将反映在两者中.



So, both the variables point to same object.
Change to any of them will be reflected in both.


因为对象是引用类型.指的是内存指针.

当您在t2中分配t1时. t2和t1拥有相同的指针(内存地址ref).当我们更改t1值时,t2将自动更改.
Because Object is of reference type. Which refer to the memory pointer.

When you assign t1 in t2. t2 and t1 hold the same pointer (memory address ref). and when we change t1 value t2 will automatically get changed.


这篇关于Java中的对象分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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