Java-Map對象紀要

關於Map對象大家最熟悉和耳熟能詳的應該是它的鍵值對存儲;
相信大家對他的一些基礎規則已經很熟悉了;
那麼今天在這裏簡單的寫一個小Demo把日常會用到的一些方法收斂一下;

其中主要幾個需要注意的方法如:
map.put(key, value);
map.get(Obj);
map.containsKey(Obj);
map.remove(Obj);
map.keySet();
map.entrySet();
Entry.getKey();
Entry.getValue();
以下是隨手的Demo供參考;

public static void main(String[] args) {
	
	// 實例化Map對象;
	Map map = new HashMap();
	
	// Map集合中添加元素;
	map.put("1", 11);
	map.put("2", 22);
	map.put("3", 33);
	map.put("4", 44);
	
	// 獲取Map集合中指定的key值; 
	String str = String.valueOf(map.get("3"));
//		System.out.println(str);
	
	// map.containsKey(); 判斷指定Key是否在Map集合中存在;存在return true; 不存在return false; 
	if(map.containsKey("3")){
		// 刪除Map集合中指定的鍵值對; 
		map.remove("3");
	}
	
	// 將Map集合中所有Key以Set格式返回;
	Set keySet = map.keySet();
//		System.out.println(map.keySet());
	
	// 將Map集合中所有的鍵值對元素以等式形式返Set格式;
	Set entrySet = map.entrySet();
//		System.out.println(map.entrySet());
	
	/**
	 *  Map對象的Entry對象;
	 *  Entry對象提供了getKey(),getValue()能夠直接獲取對應的鍵和對應的值;
	 */
	Set<Entry<String,Integer>> set = map.entrySet();
	
	/** 
	 * 遍歷Set對象得到每一個Entry對象;
	 * 分別獲取對象的Key和Value值;
	 */
	for(Entry<String,Integer> entry : set){
		System.out.println("Key: "+entry.getKey()+";  Value: "+entry.getValue());
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章