在Java中,在重新分配新对象之前,是否必须将null分配给引用变量?

huangapple go评论74阅读模式
英文:

Is it compulsory to assign null to a reference variable before reassigning a new object in java?

问题

重新将引用变量重新分配为null,然后再将其重新分配为新对象,是否会释放其之前所占用的内存,还是由垃圾回收器来完成?

Dog obj = new Dog("d1");
if(obj!=null)
    obj = null; // 这样会释放内存吗?
obj = new Dog("d2");

或者

Dog obj = new Dog("d1");
obj = new Dog("d2");
英文:

Will reassigning a reference variable to null before reassigning it to a new object releases the old memory which it used to hold or is it the work of Garbage Collector?

Dog obj = new Dog("d1");
if(obj!=null)
    obj = null; // will this release the memory?
obj = new Dog("d2");

OR

Dog obj = new Dog("d1");
obj = new Dog("d2");

答案1

得分: 2

不是,这不是强制的,实际上也没有任何有用的功能。

null 赋值给变量本身并不会释放内存。最多只会删除一个保持对象可访问的引用,如果它是最后一个引用,那么该对象最终可能会被垃圾回收。

但是,将任何其他引用赋值给该变量会做同样的事情(即删除对原始对象的引用),因此在重新赋值之前将其赋值为 null 是一个不必要的步骤。

英文:

No, it is not compulsory and does in fact not do anything useful.

Assigning null to a variable never on its own releases memory. At most it removes one reference that keeps an object reachable and if it was the last reference, then the object can eventually become garbage collected.

But assigning any other reference to that variable does the same thing (i.e. remove the reference to the original object), so assigning null to it before reassigning it is an unnecessary step.

答案2

得分: 1

你不必这样做!垃圾收集器会以任何方式回收内存。

即以下足够:

Dog obj = new Dog("d1");
obj = new Dog("d2");
英文:

You do not have to do this! The garbage collector will reclaim the memory either way.

i.e. the following is sufficient:

Dog obj = new Dog("d1");
obj = new Dog("d2");

huangapple
  • 本文由 发表于 2020年10月7日 16:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64240670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定