java中map的遍历

今天写完代码做find bugs时在map的遍历这方面出现了一下的一个提示:
”inefficient use of keySet iterator instead of entrySet iterator“
大概意思就是效率不高。
经过研究比较,发现以下两种方式遍历map都可以,只是效率不同而已
Map<String, Integer> catalogIds = new HashMap<String, Integer>();
方式一、
           Set<Map.Entry<String, Integer>> set = catalogIds.entrySet();
                 Iterator<Entry<String, Integer>> it = set.iterator();
                    while (it.hasNext())
                    {
                        String catalogId = it.next().getKey();
                        if (catalogIds.get(catalogId) < 2)
                        {
                            it.remove();
                            catalogIds.remove(catalogId);
                        }
                    }

方式二、
         Iterator<String> it = catalogIds.keySet().iterator();
                    while (it.hasNext())
                    {
                        String catalogId = it.next();
                        if (catalogIds.get(catalogId) < 2)
                        {
                            it.remove();
                            catalogIds.remove(catalogId);
                        }
                    }

根据find bugs提示来看,方式一比方式二的效率更高...至于为什么,作为java小菜鸟的我还在研究中...

你可能感兴趣的:(java,map,keyset,entrySet)