当前位置首页 > 爱问问> 正文

排列组合跟循环的区别 对象循环遍历

2021-11-10 00:34:52 爱问问

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

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
声明:此文信息来源于网络,登载此文只为提供信息参考,并不用于任何商业目的。如有侵权,请及时联系我们:baisebaisebaise@yeah.net