zoukankan      html  css  js  c++  java
  • HashMap遍历方式探究

    HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: 

    package com.HashMap.Test;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map.Entry;

    public class HashMapTest { public static void main(String[] args) { HashMap<Integer, Integer> hm = new HashMap<>(); for(int i=0;i<10000000;i++){ hm.put(i, i); } //方式1: long currentTimeMillisStart = System.currentTimeMillis(); Iterator<Entry<Integer, Integer>> iterator = hm.entrySet().iterator(); while(iterator.hasNext()){ Entry<Integer, Integer> next = iterator.next(); //System.out.println("key: "+next.getKey()+" value: "+next.getValue()); } long currentTimeMillisEnd =System.currentTimeMillis(); System.out.println("Time: " + (currentTimeMillisEnd-currentTimeMillisStart)); //方式2 long currentTimeMillisStart2 = System.currentTimeMillis(); Iterator<Integer> iterator2 = hm.keySet().iterator(); while(iterator2.hasNext()){ Integer next = iterator2.next(); //System.out.println("key: "+ next+" value: "+hm.get(next)); } long currentTimeMillisEnd2 =System.currentTimeMillis(); System.out.println("Time: " + (currentTimeMillisEnd2-currentTimeMillisStart2)); } }
    对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中。 
    Time: 58
    Time: 78
  • 相关阅读:
    用归并排序或树状数组求逆序对数量 poj2299
    UVA10600 次小生成树
    最小生成树求最大比率 UVALive
    求树的重心 poj 1655
    求树的直径+并查集(bfs,dfs都可以)hdu4514
    树形DP+RMQ+尺取法 hdu4123
    区间dp 51nod1021
    LCS poj1080
    最长公共子序列hdu1503
    python No handlers could be found for logger错误的解决
  • 原文地址:https://www.cnblogs.com/felixzh/p/5970050.html
Copyright © 2011-2022 走看看