HashMap是常用的容器类(集合类),遍历HashMap中的Key值,有两个方法实现:
1.
Map map = new HashMap();
for(Map.entry en:map.entrySet()){
en.getKey();
}
2.
Iterator it = map.keySet.iterator();
while(it.hasNext()){
it.next();
}
有的文章中说用entrySet()比keySet()的速度快,我也测试了一下,测试代码如下:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Description HashMap性能测试
* @author Administrator
* 2012-9-22
*/
public class HashMapDemo {
private static Map<String, Integer> map = new HashMap<String, Integer>();
/**
* map.entrySet()
*/
public static void testEntry() {
map.put("a", 3);
map.put("b", 2);
map.put("c", 1);
long start = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
for (Map.Entry en : map.entrySet()) {
String s = en.getKey() + "";
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
/**
* map.keySet()
*/
public static void testKeySet() {
map.put("a", 3);
map.put("b", 2);
map.put("c", 1);
long start = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String s = it.next() + "";
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
/**
* @param args
*/
public static void main(String[] args) {
//testEntry();
testKeySet();
}
}
测试环境:eclipse3.3+jdk6
测试结果,testEntry()的耗时为235,141,125,110,稳定值是125ms,testKeySet的耗时为141,125,156,109,稳定值是109ms,testKeySet()和testEntry()耗时差异不大, keySet() 比entrySet()反而略快一些。