您的位置 首页 java

受大神请教:Java HashMap三种循环遍历方式及其性能对比实例分析

本文实例讲述了Java hash Map三种循环遍历方式及其性能对比。分享给大家供大家参考,具体如下:

HashMap 的三种遍历方式

(1)for each map.entrySet()

 Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
  entry.getKey();
  entry.getValue();
}
  

(2)显示调用map.entrySet()的集合迭代器

  Iterator <Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
  entry.getKey();
  entry.getValue();
}
  

(3)for each map.keySet(),再调用get获取

 Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
  map.get(key);
}
  

三种遍历方式的性能测试及对比

测试环境 :Windows7 32位系统 3.2G双核CPU 4G内存,Java 7,Eclipse -Xms512m -Xmx512m

测试结果:

受大神请教:Java HashMap三种循环遍历方式及其性能对比实例分析

遍历方式结果分析
由上表可知:

  • for each entrySet与for iterator entrySet性能等价
  • for each keySet由于要再调用get(key)获取值,比较耗时(若hash 散列算法 较差,会更加耗时)
  • 在循环过程中若要对map进行删除操作,只能用for iterator entrySet(在HahsMap非 线程安全 里介绍)。

HashMap entrySet源码

 public V get(Object key) {
  if (key == null)
    return getForNullKey();
  Entry<K,V> entry = getEntry(key);
  return null == entry ? null : entry.getValue();
}
/**
 1. Returns the entry associated with the specified key in the
 2. HashMap. Returns null if the HashMap contains no mapping
 3. for the key.
 */final Entry<K,V> getEntry(Object key) {
  int hash = (key == null) ? 0 : hash(key);
  for (Entry<K,V> e = table[indexFor(hash, table.length)];
     e != null;
     e = e.next) {
    Object k;
    if (e.hash == hash &&
      ((k = e.key) == key || (key != null && key.equals(k))))
      return e;
  }
  return null;
}
  

结论

  • 循环中需要key、value,但不对map进行删除操作,使用for each entrySet
  • 循环中需要key、value,且要对map进行删除操作,使用for iterator entrySet
  • 循环中只需要key,使用for each keySet

文章来源:智云一二三科技

文章标题:受大神请教:Java HashMap三种循环遍历方式及其性能对比实例分析

文章地址:https://www.zhihuclub.com/195629.shtml

关于作者: 智云科技

热门文章

网站地图