1 HashMap
1)特性:
底層數據結構是數組+鏈表+紅黑樹運行null鍵和null值,,非線程安全,不保證有序,插入和讀取順序不保證一致,不保證有序,在擴容時,元素的順序會被重新打亂
實現原理:
Hashmap先採用算法將key散列爲一個int值,這個int值對應到數組的下標,如果散列值相同,則在該下標後連接鏈表,如果鏈表長度超過8,則構造紅黑樹,
2)基本屬性:
//默認初始化大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16、、就是2的四次方
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容器
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默認加載因子
static final int TREEIFY_THRESHOLD = 8;//這個值是從鏈表變成紅黑樹的閥門,如果大於這個值就會轉變
static final int UNTREEIFY_THRESHOLD = 6;// 紅黑樹節點小於6的時候轉鏈表
static final int MIN_TREEIFY_CAPACITY = 64;//轉換爲紅黑樹之前還得判斷數組的容量是否大於64
transient Node<K,V>[] table;//存放數據的·1底層數組
transient Set<Map.Entry<K,V>> entrySet;//通過entrySet變量,提供遍歷的功能
transient int size;//數組table的實際大小
transient int modCount;//操作次數
int threshold;//判斷是否需要調整HashMap,如果table數組還沒被分配時,閾值threshold等於數組的數組容量,反之threshold = capacity * load factor
final float loadFactor;//負載因子
Node的屬性
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
(1)hash:表示key的hash
(2)key:表示我們給出的key,就是map(key,value)中的key
(3)value:表示我們給出的value,就是map(key,value)中的value
(4)next:如果hash相同,會形成鏈表,當前鏈表節點的下一個鏈表的引用,即鏈表後繼
如果鏈表長度大於8,爲了查詢性能,會把鏈表轉爲紅黑樹(TreeNode)
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
}
(1)parent:表示節點的父節點
(2)left:表示左節點
(3)right:表示右節點
(4)prev:表示前驅節點
(5)red:表示是紅樹還是黑樹
3)構造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))//小於0或者爲空
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;//負載因子
//返回2的n次方 》=initialCapacity
this.threshold = tableSizeFor(initialCapacity);//
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
4)核心方法
1 put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//獲取key的hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //注意當key爲null是會返回0,hashmap允許key爲null進行存儲,且存在table[0]的位置。另外會對獲取的hashcode進行高低16位按位與,減小hash衝突的概率
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)//table是底層數組,判斷table是否爲空或者null
n = (tab = resize()).length;// 成立用resize()擴容
if ((p = tab[i = (n - 1) & hash]) == null)//計算插入的元素在hash桶中的位置,若該位置還沒有元素
tab[i] = newNode(hash, key, value, null);//插入
else {
Node<K,V> e; K k;
if (p.hash == hash &&//判斷該位置的第一個元素是否與我們要插入的元素相同
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//如果相同則記錄該節點到變量e
else if (p instanceof TreeNode)//否則判斷第一個節點是否爲樹類型的節點
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//如果是,則調用樹類型的插入操作
else {//否則,第一個元素既不與我們要插入的節點相同,又不是樹類型的節點,那麼去遍歷鏈表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {//若節點爲空則表示已經遍歷到鏈表的最後,此時新建一個節點並加入到末尾
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//判斷鏈表的長度是否大於8
treeifyBin(tab, hash); //將鏈表轉爲紅黑樹
break;
}
if (e.hash == hash &&//如果某個節點與我們即將插入的節點相同,則跳出循環
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key//此時e節點中記錄的是hashMap中與我們要插入的節點相同的節點,在這裏統一進行處理
V oldValue = e.value;//記錄舊的value值
if (!onlyIfAbsent || oldValue == null)//通過onlyIfAbsent與oldValue的值判斷是否要進行覆蓋
e.value = value;
afterNodeAccess(e);
return oldValue;//返回舊的值
}
}
++modCount;//代表hashMap的結構被改變
if (++size > threshold)//判斷是否要進行擴容
resize();
afterNodeInsertion(evict);
return null;
}
擴容函數
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;//記錄原來的table
int oldCap = (oldTab == null) ? 0 : oldTab.length;//判斷原來的table是否爲空,若爲空則oldCap = 0,否則oldCap = oldTab.length
int oldThr = threshold;//記錄原來的闕值
int newCap, newThr = 0;//創建變量用來記錄新的容量和闕值
if (oldCap > 0) {//判斷原來的容量是否大於0,由於HashMap是在第一次put是纔會進行初始化,因此此方法也是判斷table是要擴容還是要初始化.大於0代表已經初始化過了
if (oldCap >= MAXIMUM_CAPACITY) {//如果原來的容量大於0且大於等於最大值
threshold = Integer.MAX_VALUE;//將闕值設爲最大值,並返回原來的容量,代表該table已經不能再進行擴容
return oldTab;
}
//原來的容量乘以2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold//新的界限爲原來界限的一倍
}
//如果說oldCap爲0(代表hashMap沒有被初始化過)且原來的闕值大於0
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//否則說明我們在新建hashMap是沒有指定初始值或是我們將初始大小設爲了0
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//設爲默認值16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//闕值設爲16*0.75
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;//設置當前的闕值爲新的闕值
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//以新的容量去新建一個table數組
table = newTab;
if (oldTab != null) {//若原來的table是否爲空,代表現在是要進行擴容操作
for (int j = 0; j < oldCap; ++j) {//遍歷hash桶
Node<K,V> e;
if ((e = oldTab[j]) != null) {//遍歷每一個hash桶中的元素,並記錄第一個節點到變量e
oldTab[j] = null;//將原來的位置設爲null
if (e.next == null)//如果只有一個元素
newTab[e.hash & (newCap - 1)] = e;//計算新的位置,並插入
else if (e instanceof TreeNode)//如果是樹節點,則轉爲紅黑樹的擴容操作
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;//將每一個桶中的元素分爲兩類,擴容後的位置與原來相同則記錄到loHead,loTail這個鏈表中,擴容後與原來的位置不同則記錄到hiHead,hiTail中
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;//將loHead鏈表寫入到新的table
}
if (hiTail != null) {//將hiHead鏈表記錄到新的table
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
刪除方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//找到要刪除的元素存在p所在的下標
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//hash沒有衝突
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//定位刪除的節點
node = p;
//不止是一個節點在該位置上
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do { //遍歷鏈表
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//node要刪除的元素
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else//p的下一個元素等於要刪除的元素的下一個
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
使用迭代器對數組進行遍歷,中間不能對map進行操作
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
//修改次數不等於最後一次修改次數的話就會報錯
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);//尋找數組中不爲空的節點進行遍歷
}
return e;
}