sonar扫描的严重问题对应。
This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.
代码写这样就会报上面的严重问题
Map<String, Integer> params = new HashMap<String, Integer>(); params.put("resultID", 1); params.put("execID", 2); params.put("num", 3); Map<String, Object> mapOut = new HashMap<String, Object>(); // Map<String, Integer> 转 HashMap<String, Object> Set<String> set = params.keySet(); for (String key : set) { Integer value = params.get(key); mapOut.put(key,value); }
意思是说要避免用.get(key),可能有点脱裤子放屁的感觉。
修改后
for (Map.Entry<String, Integer> entry : params.entrySet()) { mapOut.put(entry.getKey(),entry.getValue()); }
参考这篇
https://www.cnblogs.com/dreammyone/articles/9960400.html
还有这篇
https://blog.csdn.net/jdsjlzx/article/details/34487299
This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.
解释:
很多人都这样遍历Map,没错,但是效率很低,先一个一个的把key遍历,然后在根据key去查找value,这不是多此一举么,为什么不遍历entry(桶)然后直接从entry得到value呢?它们的执行效率大概为1.5:1(有人实际测试过)。
我们看看HashMap.get方法的源代码: 1. public V get(Object key) { 2. if (key == null) 3. return getForNullKey(); 4. int hash = hash(key.hashCode()); 5. for (Entry<K,V> e = table[indexFor(hash, table.length)]; 6. e != null; 7. e = e.next) { 8. Object k; 9. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) 10. return e.value; 11. } 12. return null; 13. }
从这里可以看出查找value的原理,先计算出hashcode,然后散列表里取出entry,不管是计算hashcode,还是执行循环for以及执行equals方法,都是CPU密集运算,非常耗费CPU资源,如果对一个比较大的map进行遍历,会出现CPU迅速飚高的现象,直接影响机器的响应速度,在并发的情况下,简直就是一场灾难。
解决方法: 1. for (Map.Entry<String, JMenu> entry : menuList.entrySet()) { 2. mb.add(entry.getValue());
}
for(Map.Entry<String, List<BlackListDO>> tempEntiy: companyBlackItemsMap.entrySet()) {
String key = tempEntiy.getKey();
List<BlackListDO> eachCompanyBlackItems = tempEntiy.getValue();