第一種:
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);
}
效率低,以后盡量少使用!
下面請看實例:
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() 返回與此項對應的鍵
// entry.getValue() 返回與此項對應的值
System.out.print(entry.getValue());
}
System.out.println();
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
}
}
對于keySet其實是遍歷了2次荚藻,一次是轉為iterator屋灌,一次就從hashmap中取出key所對于的value。而entryset只是遍歷了第一次应狱,他把key和value都放到了entry中共郭,所以就快了。