JavaMap遍历速度最优解

2014-10-26 21:30:05 · 作者: · 浏览: 94

  第一种:


  Map map = new HashMap();


  Iterator iter = map.entrySet().iterator();


  while (iter.hasNext()) {


  Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey();


  Object val = entry.getValue();


  }


  效率高,以后一定要使用此种方式!


  第二种:


  Map map = new HashMap();


  Iterator iter = map.keySet().iterator();


  while (iter.hasNext()) {


  Object key = iter.next();


  Object val = map.get(key);


  }


  效率低,以后尽量少使用!


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


  public class HashMapTest {


  public static void main(String[] args) ...{


  HashMap hashmap = new HashMap();


  for (int i = 0; i < 1000; i ) ...{


  hashmap.put("" i, "thanks");


  }