Java HashMap.clear()和remove()内存有效吗? [英] Is Java HashMap.clear() and remove() memory effective?

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

问题描述

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

  / ** 
*从该地图中删除所有映射。
*此通话返回后,地图将为空。
* /
public void clear(){
modCount ++;
条目[] tab = table;
for(int i = 0; i< tab.length; i ++)
tab [i] = null;
size = 0;

$ / code>

看来,内部数组( table )的条目对象永远不会收缩。所以,当我向地图添加10000个元素时,以及在调用 map.clear()之后,它会在内部数组中保留10000个空值。所以,我的问题是,JVM如何处理这个没有任何数组的数组,因此, HashMap 内存有效吗?

解决方案

这个想法是只在你想重新使用 HashMap 时调用 clear / code>。应该只重复使用一个对象,原因与以前使用的相同,所以很可能会有大致相同数量的条目。为避免无用缩小和调整 Map 的大小,调用 clear()时,容量保持不变。



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

Consider the follwing HashMap.clear() code:

 /**
 * 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;
}

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?

解决方案

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.

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()内存有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆