2011-1-6 java遍历map所有元素
//JDK1.5后
Map map = getMap();
for(Object obj : map.keySet()) {
Object key = obj;
Object value = map.get(obj);
}
//JDK1.5之前
Map map = getMap();
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object value = entry.getValue();
}
遍历K-V
/* 第一种: entryset只遍历一次:它把key和value放到entry */
Map map = getMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}//高效,使用此种方式
/* 第二种: keySet实际遍历了2次:
转为iterator时候一次;
取key对应value又一次。*/
Map map = getMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}//效率低