英文:
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");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论