今天在网上看到一则遍历hashmap去Value时,用keyset的效率比用entryset低,后来测试了一遍,发觉其实不能一概而论
以下是多次执行代码,结果值有所不同
按照网上的例子,hm.put(i, "thans");
entrySet:消耗时间毫秒:16
keyset:消耗时间毫秒:31
entrySet:消耗时间毫秒:47
keyset:消耗时间毫秒:15
public void testHashMap(){
HashMap hm= new HashMap();
for(int i=0;i<1000;i++){
hm.put(i, "abc");
}
System.out.println("entrySet:");
long bs = Calendar.getInstance().getTimeInMillis();
Iterator it = hm.entrySet().iterator();
while(it.hasNext()){
Entry entry = (Entry)it.next();
//System.out.print(entry.getKey()+"["+entry.getValue()+"] ");
System.out.print("["+entry.getValue()+"] ");
}
System.out.println();
System.out.println("消耗时间毫秒:");
System.out.println(Calendar.getInstance().getTimeInMillis()-bs);
//System.out.println("取key=0:"+hm.get(0).toString());
System.out.println("keyset:");
long bs2 = Calendar.getInstance().getTimeInMillis();
Iterator it2 = hm.keySet().iterator();
while(it2.hasNext()){
Integer ks = (Integer)it2.next();
System.out.print("["+hm.get(ks)+"] ");
}
System.out.println();
System.out.println("消耗时间毫秒:");
System.out.println(Calendar.getInstance().getTimeInMillis()-bs2);