import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
for(int i=0;i<10000;i++){
map.put(i+"", i);
}
long begin1 = System.currentTimeMillis();
Set<String> keyset = map.keySet();
Iterator<String> it = keyset.iterator();
while(it.hasNext()){
String k = it.next();
System.out.println(map.get(k));
}
long end1 = System.currentTimeMillis();
long begin2 = System.currentTimeMillis();
Set<Map.Entry<String, Integer>> entries = map.entrySet();
Iterator<Map.Entry<String, Integer>> it2 = entries.iterator();
while(it2.hasNext()){
Map.Entry<String, Integer> next = it2.next();
System.out.println(next.getKey()+"---"+next.getValue());
}
long end2 = System.currentTimeMillis();
System.out.println((end1-begin1)+"---"+(end2-begin2));;
}
}
执行时间,用keySet方式遍历要比entrySet的方式用时大两倍!
时间差在,keySet方式要再从Map里面获取一遍。