遍历一个HashMap

可以通过2种方法遍历HashMap

Map map = new HashMap();

for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {

Map.Entry entry = (Map.Entry) iter.next();

Object key = entry.getKey();

Object val = entry.getValue();

}

或者:

Map map = new HashMap();

for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {

Object key = iter.next();

Object val = map.get(key);

}

一个遍历hashmap的例子:
HashMap h = new HashMap();
h.put("1", "1aaaa");
h.put("2", "2222");<?XML:NAMESPACE PREFIX = O />


Iterator it = h.keySet().iterator();
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj + ": " + h.get(obj));
}

你可能感兴趣的:(HashMap)