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

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

问题描述

如果我这样做会发生什么:

What happens if I do:

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

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

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

更正式地,考虑一下代码:

More formally, consider the code:

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天全站免登陆