<strong><span style="font-size:18px;">HashMap的几种变例方式!! 原文出处!若侵权请联系我!http://www.cnblogs.com/kristain/articles/2033566.html</span></strong>
</pre><pre name="code" class="java">public class TestHashMap {
public static void main(String[] args) {
Map<Integer, String> en = new HashMap<Integer, String>();
en.put(11, "AA");
en.put(22, "BB");
en.put(33, "CC");
en.put(null, null);
en.put(null, null);
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (Integer key : en.keySet()) {
System.out.println("key= "+ key + " and value= " + en.get(key));
}
/* 结果
* key= null and value= null
key= 33 and value= CC
key= 22 and value= BB
key= 11 and value= AA
*/
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Entry<Integer, String>> it = en.entrySet().iterator();
while (it.hasNext()) {
Entry<Integer, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
/*
* 通过Map.entrySet使用iterator遍历key和value:
key= null and value= null
key= 33 and value= CC
key= 22 and value= BB
key= 11 and value= AA
*/
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Entry<Integer, String> entry : en.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
/*
* 通过Map.entrySet遍历key和value
key= null and value= null
key= 33 and value= CC
key= 22 and value= BB
key= 11 and value= AA
*/
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : en.values()) {
System.out.println("value= " + v);
}
/*
* 通过Map.values()遍历所有的value,但不能遍历key
value= null
value= CC
value= BB
value= AA
*/
}
}