今天需要遍歷壹個Hashtable,查看了壹下Hashtable類,發現它提供了如下幾個方法可供我們遍歷:
keys() – returns an Enumeration of the keys of this Hashtable
keySet() – returns a Set of the keys
entrySet() – returns a Set of the mappings
elements() – returns an Enumeration of the values of this Hashtable
4種方法,那種更好呢,寫段代碼來比較壹下吧:
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
public class traveseHashTable {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<String, String>();
for (int i = 0; i < 10000; i++) {
ht.put(“Key=” + i, “Val=” + i);
}
// 1. Enumeration
long start = System.currentTimeMillis();
Enumeration<String> en = ht.keys();
while (en.hasMoreElements()) {
en.nextElement();
}
long end = System.currentTimeMillis();
System.out.println(“Enumeration keys costs ” + (end – start)
+ ” milliseconds”);
// 2. Enumeration
start = System.currentTimeMillis();
Enumeration<String> en2 = ht.elements();
while (en2.hasMoreElements()) {
en2.nextElement();
}
end = System.currentTimeMillis();
System.out.println(“Enumeration elements costs ” + (end – start) + ” milliseconds”);
// 3. Iterator
start = System.currentTimeMillis();
Iterator<String> it = ht.keySet().iterator();
while (it.hasNext()) {
it.next();
}
end = System.currentTimeMillis();
System.out.println(“Iterator keySet costs ” + (end – start) + ” milliseconds”);
// 4. Iterator
start = System.currentTimeMillis();
Iterator<Entry<String, String>> it2 = ht.entrySet().iterator();
while (it2.hasNext()) {
it2.next();
}
end = System.currentTimeMillis();
System.out.println(“Iterator entrySet costs ” + (end – start) + ” milliseconds”);
}
}
這裏創建了壹個10000個元素的Hashtable來供我們遍歷,打印出結果如下:
Enumeration keys costs 6 milliseconds
Enumeration elements costs 5 milliseconds
Iterator keySet costs 10 milliseconds
Iterator entrySet costs 10 milliseconds
我們看到,通過叠代來遍歷比枚舉要多花盡壹倍的時間。所以建議大家最好通過枚舉類來遍歷Hashtable哦。