将变量设置为null是否仅清除引用? [英] Does setting variable to null clear just the reference?

查看:62
本文介绍了将变量设置为null是否仅清除引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做会怎样:

Object obj = new Object();
obj = null;

它是从内存中删除对象还是仅清除引用?

Does it remove the object from memory, or clear just the reference?

更正式地考虑代码:

Object obj = new Object();
Object temp = obj;
obj = null;

为什么 temp 仍然不是 null ?不应该将其从内存中删除吗?

Why is temp still not null? Shouldn't it have been removed from memory?

推荐答案

在您的第一个示例中:

obj -------> |OBJECT|

obj 设置为 null 后:

obj          |OBJECT|

不存在对该对象的引用,因此该对象不再存在,因此不再存在".

No reference to the object exists so it "doesn't exist" anymore because it has become unreachable.

在第二个示例中:

obj -------> |      |
             |OBJECT|
temp ------> |      |

obj 设置为 null 后:

obj          |      |
             |OBJECT|
temp ------> |      |

您可以看到 temp 仍引用该对象,因此它仍然存在".

You can see that temp still references the object so it still "exists".

这篇关于将变量设置为null是否仅清除引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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