①對HashMap的整體認識
HashMap是一個散列表,它存儲的內容是鍵值對(key-value)映射。
HashMap繼承於AbstractMap,實現了Map、Cloneable、java.io.Serializable接口。
HashMap的實現是不同步的,這意味着它不是線程安全的。它的key,value都可以是null。此外,HashMap中的映射不是有序的。
HashMap的實例有兩個參數影響其性能:“初始容量”和“加載因子”。初始容量是哈希表在創建時的容量。加載因子是哈希表在其容量自動增加之前可以達到多滿的一種尺度。通常默認加載因子是0.75,這是在時間和空間成本上尋求一種折衷。
②HashMap的構造函數
// 默認構造函數。
HashMap()
// 指定“容量大小”的構造函數
HashMap(int capacity)
// 指定“容量大小”和“加載因子”的構造函數
HashMap(int capacity, float loadFactor)
// 包含“子Map”的構造函數
HashMap(Map<? extends K, ? extends V> map)
③HashMap的API
void clear()
Object clone()
boolean containsKey(Object key)
boolean containsValue(Object value)
Set<Entry<K, V>> entrySet()
V get(Object key)
boolean isEmpty()
Set<K> keySet()
V put(K key, V value)
void putAll(Map<? extends K, ? extends V> map)
V remove(Object key)
int size()
Collection<V> values()
④ HashMap的繼承關系
java.lang.Object
↳ java.util.AbstractMap<K, V>
↳ java.util.HashMap<K, V>
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable { }
HashMap繼承於AbstractMap類,實現了Map接口。Map是"key-value鍵值對"接口,AbstractMap實現了"鍵值對"的通用函數接口
HashMap是通過“拉鏈法”實現的哈希表。它包括幾個重要的成員變量:table,size,threshold,loadFactor,modCount。
Table是一個Entry[]數組類型,Entry是一個單向鏈表。哈希表的key-value鍵值對都是存儲在Entry數組中的。
Size是HashMap的大小 ,它是HashMap保存的鍵值對的數量。
Threshold是HashMap的閾值,用於判斷是否需要調整HashMap的容量。Threshold的值=“容量*加載因子”,當HashMap中存儲數據的數量達到threshold時,需要將HashMap的容量加倍。
loadFactor就是加載因子。
modCount是用來實現fail-fast機制的。
⑤HashMap遍歷方式
1 遍歷HashMap的鍵值對
第一步:根據entrySet()獲取HashMap的“鍵值對”的Set集合。
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。
// 假設map是HashMap對象
// map中的key是String類型,value是Integer類型
Integer integ = null;
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
// 獲取key
key = (String)entry.getKey();
// 獲取value
integ = (Integer)entry.getValue();
}
2 遍歷HashMap的鍵
第一步:根據keySet()獲取HashMap的“鍵”的Set集合。
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。
// 假設map是HashMap對象
// map中的key是String類型,value是Integer類型
String key = null;
Integer integ = null;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
// 獲取key
key = (String)iter.next();
// 根據key,獲取value
integ = (Integer)map.get(key);
}
3 遍歷HashMap的值
第一步:根據value()獲取HashMap的“值”的集合。
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。
// 假設map是HashMap對象
// map中的key是String類型,value是Integer類型
Integer value = null;
Collection c = map.values();
Iterator iter= c.iterator();
while (iter.hasNext()) {
value = (Integer)iter.next();
}
⑥遍歷測試程序如下:
import java.util.Map;
import java.util.Random;
import java.util.Iterator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Collection;
/*
* @desc 遍歷HashMap的測試程序。
* (01) 通過entrySet()去遍歷key、value,參考實現函數:
* iteratorHashMapByEntryset()
* (02) 通過keySet()去遍歷key、value,參考實現函數:
* iteratorHashMapByKeyset()
* (03) 通過values()去遍歷value,參考實現函數:
* iteratorHashMapJustValues()
*
* @author skywang
*/
public class HashMapIteratorTest {
public static void main(String[] args) {
int val = 0;
String key = null;
Integer value = null;
Random r = new Random();
HashMap map = new HashMap();
for (int i=0; i<12; i++) {
// 隨機獲取一個[0,100)之間的數字
val = r.nextInt(100);
key = String.valueOf(val);
value = r.nextInt(5);
// 添加到HashMap中
map.put(key, value);
System.out.println(" key:"+key+" value:"+value);
}
// 通過entrySet()遍歷HashMap的key-value
iteratorHashMapByEntryset(map) ;
// 通過keySet()遍歷HashMap的key-value
iteratorHashMapByKeyset(map) ;
// 單單遍歷HashMap的value
iteratorHashMapJustValues(map);
}
/*
* 通過entry set遍歷HashMap
* 效率高!
*/
private static void iteratorHashMapByEntryset(HashMap map) {
if (map == null)
return ;
System.out.println("\niterator HashMap By entryset");
String key = null;
Integer integ = null;
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
key = (String)entry.getKey();
integ = (Integer)entry.getValue();
System.out.println(key+" -- "+integ.intValue());
}
}
/*
* 通過keyset來遍歷HashMap
* 效率低!
*/
private static void iteratorHashMapByKeyset(HashMap map) {
if (map == null)
return ;
System.out.println("\niterator HashMap By keyset");
String key = null;
Integer integ = null;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
key = (String)iter.next();
integ = (Integer)map.get(key);
System.out.println(key+" -- "+integ.intValue());
}
}
/*
* 遍歷HashMap的values
*/
private static void iteratorHashMapJustValues(HashMap map) {
if (map == null)
return ;
Collection c = map.values();
Iterator iter= c.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
⑦通過一個實例學習如何使用HashMap
import java.util.Map;
import java.util.Random;
import java.util.Iterator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Collection;
/*
* @desc HashMap測試程序
*
* @author skywang
*/
public class HashMapTest {
public static void main(String[] args) {
testHashMapAPIs();
}
private static void testHashMapAPIs() {
// 初始化隨機種子
Random r = new Random();
// 新建HashMap
HashMap map = new HashMap();
// 添加操作
map.put("one", r.nextInt(10));
map.put("two", r.nextInt(10));
map.put("three", r.nextInt(10));
// 打印出map
System.out.println("map:"+map );
// 通過Iterator遍歷key-value
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
System.out.println("next : "+ entry.getKey() +" - "+entry.getValue());
}
// HashMap的鍵值對個數
System.out.println("size:"+map.size());
// containsKey(Object key) :是否包含鍵key
System.out.println("contains key two : "+map.containsKey("two"));
System.out.println("contains key five : "+map.containsKey("five"));
// containsValue(Object value) :是否包含值value
System.out.println("contains value 0 : "+map.containsValue(new Integer(0)));
// remove(Object key) : 刪除鍵key對應的鍵值對
map.remove("three");
System.out.println("map:"+map );
// clear() : 清空HashMap
map.clear();
// isEmpty() : HashMap是否為空
System.out.println((map.isEmpty()?"map is empty":"map is not empty") );
}
}
運行結果
map:{two=7, one=9, three=6}
next : two - 7
next : one - 9
next : three - 6
size:3
contains key two : true
contains key five : false
contains value 0 : false
map:{two=7, one=9}
map is empty