我不知道如何搜索这个问题,所以我提出了一个问题。
Java版本1.7.0_80_x86
java.util.Hashtable
中的 remove
方法;
我看到节点 e
的 value 属性设置为 null
;
但是,e.next
未设置为 null;
那么如果e.next
不为null,节点e
会不会被gc回收呢?
方法源码:
/**
* Removes the key (and its corresponding value) from this
* hashtable. This method does nothing if the key is not in the hashtable.
*
* @param key the key that needs to be removed
* @return the value to which the key had been mapped in this hashtable,
* or <code>null</code> if the key did not have a mapping
* @throws NullPointerException if the key is <code>null</code>
*/
public synchronized V remove(Object key) {
Entry tab[] = table;
int hash = hash(key);
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
最佳答案
每一棵对象树都必须有一个或多个根对象。只要应用程序可以到达这些根,它们就被视为 Activity 对象,如果应用程序无法到达这些根,那么它们就会被垃圾收集器收集。所以你的问题的答案是肯定的“e”将被GC垃圾收集。但“e.next”可能会也可能不会被 GC 垃圾收集。如果它们是对“e.next”(“e”除外)的引用,那么它不会被 GC 收集为垃圾。
关于Java源码哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51353795/