本文介绍了Java HashMap.clear() 和 remove() 内存有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 HashMap.clear() 代码:

 /**
 * Removes all of the mappings from this map.
 * The map will be empty after this call returns.
 */
public void clear() {
    modCount++;
    Entry[] tab = table;
    for (int i = 0; i < tab.length; i++)
        tab[i] = null;
    size = 0;
}

看起来,Entry 对象的内部数组 (table) 永远不会缩小.因此,当我向地图添加 10000 个元素并在调用 map.clear() 之后,它将在其内部数组中保留 10000 个空值.所以,我的问题是,JVM 如何处理这个空数组,因此 HashMap 内存是否有效?

It seems, that the internal array (table) of Entry objects is never shrinked. So, when I add 10000 elements to a map, and after that call map.clear(), it will keep 10000 nulls in it's internal array. So, my question is, how does JVM handle this array of nothing, and thus, is HashMap memory effective?

推荐答案

这个想法是 clear() 只在你想重用 HashMap 时调用.重用对象的原因应该与之前使用的原因相同,因此您可能会拥有大致相同数量的条目.为了避免 Map 的无用缩小和调整大小,调用 clear() 时容量保持不变.

The idea is that clear() is only called when you want to re-use the HashMap. Reusing an object should only be done for the same reason it was used before, so chances are that you'll have roughly the same number of entries. To avoid useless shrinking and resizing of the Map the capacity is held the same when clear() is called.

如果您只想丢弃 Map 中的数据,那么您不需要(实际上也不应该)对其调用 clear(),但是只需清除对 Map 本身的所有引用,在这种情况下,它最终将被垃圾收集.

If all you want to do is discard the data in the Map, then you need not (and in fact should not) call clear() on it, but simply clear all references to the Map itself, in which case it will be garbage collected eventually.

这篇关于Java HashMap.clear() 和 remove() 内存有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:49