三种HashMap循环遍历方法的分析及其性能比较示例

电脑杂谈  发布时间:2020-05-01 05:19:43  来源:网络整理

java map 遍历_map循环遍历_map.entry 遍历

更新时间: 2019年10月29日12:04:29作者: xuexuan_050848

本文主要介绍Java HashMap的三种循环遍历方法及其性能比较. 结合具体的示例形式,对Java HashMap的三种循环遍历方法的实现方法,运行效率以及性能优缺点进行了分析. 下一个

本文介绍了Java HashMap的三种循环遍历方法及其性能比较. 与您分享以供参考,如下:

HashMap的三种遍历方法

每个地图

(1).entrySet()

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

java map 遍历_map.entry 遍历_map循环遍历

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

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

(3)每个map.keySet()map循环遍历,然后调用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

测试结果:

map循环遍历_java map 遍历_map.entry 遍历

地图尺寸

10,000

100,000

1,000,000

2,000,000

每个条目集

用于迭代器entrySet

java map 遍历_map循环遍历_map.entry 遍历

每个键集

126ms

遍历结果分析

上表:

HashMap条目设置源代码

private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
  public Map.Entry<K,V> next() {
    return nextEntry();
  }
}

HashMap keySet源代码

map.entry 遍历_java map 遍历_map循环遍历

private final class KeyIterator extends HashIterator<K> {
  public K next() {
    return nextEntry().getKey();
  }
}

从源代码开始:

keySet()和entrySet()都是返回set的迭代器. 父类相同,但是返回值不同,因此性能相似. 只是keySet()根据密钥获取值操作又有一个步骤. get的时间复杂度取决于for循环的数量map循环遍历,这是哈希算法.

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;
}

结论

对更多Java相关内容感兴趣的读者可以查看此站点的主题: “ Java数据结构和算法教程”,“关于DOM节点的Java操作摘要”,“ Java文件和目录操作技巧摘要”和“ Java缓存操作”提示摘要“

我希望本文对Java编程的每个人都有帮助.


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-194909-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...