《HashMap的常用操作》

package com.sufow.test;

import java.util.HashMap;
import java.util.Map;

/***
 * HashMap的一些常用方法的使用
 * @author Administrator
 *
 */
public class MapTest2 {


	public static void main(String[] args) {

		Map<String,String> hashMap = new HashMap<String,String>();


		//插入相關操作,插入一個元素
		hashMap.put("sufow1", "舒泉1");
		hashMap.put("sufow2", "舒泉2");
		hashMap.put("sufow3", "舒泉3");
		hashMap.put("sufow4", "舒泉4");
		hashMap.put("sufow5", "舒泉5");

		//插入一個map對象
		Map map2 = new HashMap();
		map2.put("sufow6", "舒泉6");
		hashMap.putAll(map2);

		//獲取相關操作(entrySet()、get()、keySet()、size()、values())

		System.out.println("------第一種entrySet---------");
		for(Map.Entry<String, String> map:hashMap.entrySet()){
			System.out.println(map.getValue());
		}

		System.out.println("------第二種keySet----------");
		for(String str:hashMap.keySet()){
			System.out.println(hashMap.get(str));
		}

		System.out.println("------第三種values----------");
		for(String str:hashMap.values()){
			System.out.println(str);
		}

		//獲取size
		System.out.println("Map的size爲:"+hashMap.size());

		//判斷操作(containsKey()、containsValue()、equals()、isEmpty())

		if(hashMap.containsKey("sufow3")){
			System.out.println("包含key爲sufow3的值爲"+hashMap.get("sufow3"));
		}else{
			System.out.println("不包含key爲sufow3的鍵");
		}

		if(hashMap.containsValue("舒泉4")){
			System.out.println("包含值爲舒泉4");
		}else{
			System.out.println("不包含值爲舒泉4");
		}

		if(hashMap.isEmpty()){
			System.out.println("Map對象爲空");
		}else{
			System.out.println("Map對象不爲空");
		}


		//清除操作
		map2.clear();
		if(map2.isEmpty()){
			System.out.println("Map2對象爲空");
		}else{
			System.out.println("Map2對象不爲空");
		}
		
		
		//移除操作
		
		hashMap.remove("sufow5");//移除key爲sufow5的元素
		
		System.out.println("移除後:"+hashMap.toString());
	}
}

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