1.HashMap簡介
- HashMap繼承了AbstractMap類該類實現了Map接口,HashMap同時實現了Map接口。
- HashMap是key,value結構的鍵值對,支持key和value都為null
- HashMap和HashTable功能很相近,可以把它看做非線程安全的HashTable和允許key,value為空。
2.分析下HashMap的內部結構
hashmap結構圖.png
HashMap有兩個重要的參數:一個是加載因子,另一個是初始容量
//初始容量為16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//默認加載因子是0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
3.HashMap的構造函數
//設置初始容量和加載因子
public HashMap(int initialCapacity, float loadFactor)
//設置初始容量和默認加載因子
public HashMap(int initialCapacity)
//默認構造,使用默認容量和默認加載引起
public HashMap()
//使用已經存在的map創建新的map
public HashMap(Map<? extends K, ? extends V> m)
4.HashMap主要對外接口
4.1 get方法
public V get(Object key) {
//如果key是null的話
if (key == null)
return getForNullKey();
//key不為空調用getEntry方法
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
private V getForNullKey() {
//判斷大小
if (size == 0) {
return null;
}
//null存在table[0]上,返回value的值
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
final Entry<K,V> getEntry(Object key) {
//如果map的size為0,那么就直接返回null
if (size == 0) {
return null;
}
//計算hash值
int hash = (key == null) ? 0 : hash(key);
//獲取到hash值對應的table中的鏈表
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
//遍歷該鏈表,判斷key是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
5.HashMap存儲數據是無序的我們看下代碼的例子
HashMap<String,Integer> store = new HashMap<String,Integer>();
store.put("22", 33);
store.put("44", 44);
store.put("55", 55);
for(Map.Entry<String,Integer> ele :store.entrySet()) {
System.out.println(ele.getKey() + "--" + ele.getValue());
}
運行結果如下:
44--44
55--55
22--33
說明并不是按照我們存儲的順序存儲的。