清除集合对象中的引用

Clearing references in the collection objects

我有一个 Student 类型的 HashMap。 Student 是一个用户定义对象,它由几个 属性 和另一个名为 College 的用户定义对象组成。现在,在使用之后,我想清除 HashMap 使用的所有内存,进而清除 Student 和 College 对象使用的所有内存。因此,在取消时,我是否需要显式取消 Student 和 College 对象,然后将 NULL 引用分配给 HashMap 对象?或者只给HashMap对象赋NULL也会释放Student和College对象占用的内存?

Map<String, Student> myMap = new HashMap<String, Student>
Student std = myMap.get("");
College col = std.getCollege();
col = null; std = null;
myMap = null;

我是否需要执行以上所有操作才能释放 HashMap 正在使用的内存?或者取消HashMap会释放所有内存?

我只是挖掘出这个问题的答案并了解到,当我们在任何 hashmap 对象上调用 clear 方法时,它会在内部迭代 hashmap 中的所有 object/contents 并将其显式分配给 NULL。然后将 hashMap 的大小设置为 0 以清除哈希映射。下面是HashMapclass.

的clear()方法的实现
public void clear() {
    this.modCount += 1;
    Entry[] arrayOfEntry = this.table;
    for (int i = 0; i < arrayOfEntry.length; ++i)
        arrayOfEntry[i] = null;
    this.size = 0;
}

你可以在你的eclipse中使用jadclipse插件查看HashMap的这个内容class