算不上是原創,但畢竟是自己寫的代碼,所以厚着臉皮寫成原創了。
說一個小快捷方式:
Myeclipse 的快捷反向生成,如map.entrySet().iterator(); 根據這個方法的返回值,按Alt+Shift+L 能自動生成返回的類型。
Map的循環遍歷:
Map<String, Object> map = new HashMap<String, Object>();
map.put("a1", 1);
map.put("a2", 2);
map.put("a3", 3);
map.put("a4", 4);
//循環遍歷Map集合,通過entrySet()返回得到Entry類型
//Map.Entry是Map聲明的一個內部接口,此接口爲泛型,定義爲Entry<K,V>。
Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String, Object> next = iterator.next();
System.out.println("Key 值:"+next.getKey()+" Value 值:"+next.getValue());
}
//循環遍歷Map集合,通過keySet()返回得到全部Key值
Iterator<String> iterator2 = map.keySet().iterator();
while(iterator2.hasNext()){
String key = iterator2.next();
//通過Key值,得到Value值
System.out.println(map.get(key));
}
//還有一個values()方法,得到全部的Value值</span>
Map的一些判斷方法:
//判斷是有該 Key
boolean containsKey = map.containsKey("a1");
//判斷是否有該 Value
boolean containsValue = map.containsValue("2");
//返回該Map集合的長度
int size = map.size();
//判斷該Map集合是否有值
boolean empty = map.isEmpty();</span>