接下来对两种方式做一个对比试验:
Mapmap=new HashMap(); for(int i=0;i<10000000;i++){ map.put("a"+i, "b"+i); } Long a =System.currentTimeMillis(); Setset=map.keySet(); for(String str:set){ map.get(str); } set=null; Long b=System.currentTimeMillis(); System.out.println(b+" b-a = "+(b-a)); Set>entrySet=map.entrySet(); for(Entryentry:entrySet){ entry.getValue(); } Long c=System.currentTimeMillis(); map=null; System.out.println(c+ " c-b = "+(c-b));
对比结果如下图所示,通过第二种方式比第一种方式快15ms。