在Java中清除嵌套地图的好方法 [英] Good way to clear nested Maps in Java

查看:206
本文介绍了在Java中清除嵌套地图的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class MyCache {

AbstractMap< String,AbstractMap< String,Element>> cache = new TreeMap< String,AbstractMap< String,
Element>>();

public Boolean putElement(String targetNamespace,Element element){
...
}

public void clear(){
cache 。明确();
}

//这样更好吗?

public void deepClear(){
for(AbstractMap< String,Element> innerMap:cache.values()){
innerMap.clear();
}
cache.clear();
}
}

是否需要迭代根的值先映射并清除嵌套在根目录中的所有地图,还是足以清除最外面的地图?
我的主要问题是,如果这两种方法之间JVM的内存消耗有任何差异吗?

解决方案

这两种方法是相同的。假设没有对象(在地图本身旁边)保持对嵌套地图的引用,一旦第一个地图被清除,它所包含的所有地图都有资格被垃圾收集,因此,这些地图所持有的所有对象都被引用。 / p>

public class MyCache {

    AbstractMap<String, AbstractMap<String, Element>> cache = new TreeMap<String, AbstractMap<String,
            Element>>();

    public Boolean putElement(String targetNamespace, Element element) {
        ...
    }

    public void clear() {
        cache.clear();
    }

    // is it better this way?

    public void deepClear() {
        for(AbstractMap<String, Element> innerMap : cache.values()) {
            innerMap.clear();
        }
        cache.clear();
    }
}

Is it necessary to iterate over the values of the root map and clear all the maps nested in the root first, or is it enough to clear the outermost map? My main question is, if there is any difference in the memory consumption of the JVM between these two methods?

解决方案

The two approaches are identical. Assuming no objects (beside the maps themselves) hold references to the nested maps, once the first map is cleared, all the maps it contained are eligible to be garbage collected and so are, consequently, all objects that those maps held references to.

这篇关于在Java中清除嵌套地图的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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