第一種:(效率高,以后一定要使用此種方式!)
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
第二種:(效率低,以后盡量少使用<テ辍)
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
HashMap的遍歷有兩種常用的方法啼器,那就是使用keyset及entryset來進行遍歷,但兩者的遍歷速度是有差別的告丢,下面請看實例:
public class HashMapTest {
public static void main(String[] args) {
HashMap hashmap = new HashMap();
for (int i = 0; i < 1000; i ){
hashmap.put("" i, "thanks");
}
long bs = Calendar.getInstance().getTimeInMillis();
Iterator iterator = hashmap.keySet().iterator();
while (iterator.hasNext()){
System.out.print(hashmap.get(iterator.next()));
}
System.out.println();
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
listHashMap();
}
public static void listHashMap() {
java.util.HashMap hashmap = new java.util.HashMap();
for (int i = 0; i < 1000; i ) {
hashmap.put("" i, "thanks");
}
long bs = Calendar.getInstance().getTimeInMillis();
java.util.Iterator it = hashmap.entrySet().iterator();
while (it.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
// entry.getKey() 返回與此項對應(yīng)的鍵
// entry.getValue() 返回與此項對應(yīng)的值
System.out.print(entry.getValue());
}
System.out.println();
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
}
}
對于keySet其實是遍歷了2次岖免,一次是轉(zhuǎn)為iterator颅湘,一次就從hashmap中取出key所對于的value。而entryset只是遍歷了第一次栅炒,他把key和value都放到了entry中术羔,所以就快了级历。