1. 程式人生 > >Java中HashMap的常用操作

Java中HashMap的常用操作

前期準備:首先給hashMap裡面put一些鍵值對,程式碼如下:

HashMap<Integer, Integer> hashMap = new HashMap<>();
		
		hashMap.put(5, 2);
		hashMap.put(9, 2);
		hashMap.put(8, 1);
		hashMap.put(7, 3);
		hashMap.put(16, 1);
		hashMap.put(10, 2);
		hashMap.put(6, 2);
		//其實下面兩個鍵值對是沒有存的
		hashMap.put(5, 2);
		hashMap.put(5, 3);

當在hashmap中put的key在之前已經存過,則不會重複儲存會覆蓋之前key對應的value,詳情請參照原始碼

1.containsKey(Object key)方法,返回值為boolean,用於判斷當前hashmap中是否包含key對應的key-value

2.containsValue(Object value)方法,返回值為boolean,用於判斷當前hashmap中是否包含value對應的key-value

3.遍歷hashmap的兩種方式:

(1)利用haspmap.entrySet().iterator():利用迭代器,從Entry中取出鍵、取出值,推薦使用這種方式進行遍歷,效率較高

Iterator<Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<Integer, Integer> entry = iterator.next();
			Integer key = entry.getKey();
			Integer value = entry.getValue();
			System.out.print(key + "--->" + value);
			System.out.println();
		}
(2)利用hashmap.keySet().iterator():利用鍵的迭代器,每次取出一個鍵,再根據鍵,從hashmap中取出值,這種方式的效率不高,不推薦使用
Iterator<Integer> iterator2 = hashMap.keySet().iterator();
		while (iterator2.hasNext()) {
			Integer key = iterator2.next();
			Integer value = hashMap.get(key);
			System.out.print(key + "---" + value);
			System.out.println();
		}