龙空技术网

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

Java盘鱼宴 633

前言:

眼前姐妹们对“java循环遍历object”可能比较重视,兄弟们都需要分析一些“java循环遍历object”的相关资讯。那么小编在网摘上网罗了一些关于“java循环遍历object””的相关文章,希望看官们能喜欢,各位老铁们快快来了解一下吧!

本文实例讲述了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

测试结果:

遍历方式结果分析

由上表可知:

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循环遍历object