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());
	}
}

 

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