取消引用数组中的对象以进行Java垃圾收集

TIE*_*011 6 java arrays garbage-collection dereference

我已经对java垃圾收集器做了一些研究,并了解不再引用的对象将/应该由垃圾收集器处理.就对象数组而言,我知道将新对象分配给数组中的某个位置并不能正确释放先前分配的对象.

  1. 我想知道如何从x位置的数组中删除并正确释放对象,并将新对象分配给位置x的同一个数组.
  2. 我还想知道如何正确释放数组本身.

Jac*_*ack 9

将数组中的对象设置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
Run Code Online (Sandbox Code Playgroud)

垃圾收集很少会回收当地人的记忆,所以垃圾收集主要发生在函数范围之外.

  • 好答案.任何对象的归零都会删除对对象的引用,并使其成为垃圾回收的候选对象.+1 (2认同)