我对 java 垃圾收集器做了一些研究,了解到不再引用的对象将/应该由垃圾收集器处理。就对象数组而言,我知道将新对象分配给数组中的某个位置并不能正确释放先前分配的对象。
- 我想知道如何从位置 x 的数组中删除并正确解除分配对象,以及如何将新对象分配给位置 x 的同一数组。
- 我还想知道如何正确地释放数组本身。
最佳答案
将数组中的对象设置为 null
或另一个对象使其符合垃圾回收条件,假设没有对存储在任何地方的同一对象的引用。
如果你有
Object[] array = new Object[5];
Object object = new Object() // 1 reference
array[3] = object; // 2 references
array[1] = object; // 3 references
object = null; // 2 references
array[1] = null; // 1 references
array[3] = new Object(); // 0 references -> eligible for garbage collection
array = null; // now even the array is eligible for garbage collection
// all the objects stored are eligible too at this point if they're not
// referenced anywhere else
尽管垃圾回收很少会回收局部内存,因此垃圾回收大多已经发生在函数范围之外。
关于java - 取消引用数组中的对象以进行 Java 垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790314/