集合的作用就是以一定的方式組織,存儲數據。對於HashMap,我認爲需要的關注以下內容:
1.集合的基本存儲單元
2.集合的增刪改查基本操作的實現
3.存儲數據的要求,是否爲空,是否允許重複
4.存放與讀取是否有序
5.是否線程安全
首先,我在這裏介紹下集合的家庭族譜。總的來說,java中所用的集合,都是實現了Collection接口的,類繼承圖如下:
基本存儲單元
HashMap的源碼片段:
/** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size; /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ transient int modCount; /** * The next size value at which to resize (capacity * load factor). * * @serial */ // (The javadoc description is true upon serialization. // Additionally, if the table array has not been allocated, this // field holds the initial array capacity, or zero signifying // DEFAULT_INITIAL_CAPACITY.) int threshold; /** * The load factor for the hash table. * * @serial */ final float loadFactor;
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next;}
基於Node數組和Node鏈表的實現。
集合的增刪改查基本操作的實現
1.新增元素
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) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) 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; 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 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 V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
先用hash算法取出Node數組下標index;如果當前數組下標爲index的Node不存在數據,即無hash衝突,新建Node直接放入此數組中,當然,這個Node的next爲null。接下來討論hash值衝突的情況:1.hash值衝突而且key值相同,此時將此Node的value用新的值覆蓋;2.hash值衝突但key值不同,此時需要新建一個Node,並將上一個Node的next指向當前新建的newNode,作爲鏈表實現。
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
Hash算法。
2.修改元素
同put方法,直接覆蓋value值。
3.刪除元素
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; 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; 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); } } 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.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; }
通過key計算出hash,通過hash計算中數組index下標。取出數組index裏的第一個元素,如果key與第一個元素的key相同,而且此index不存在hash衝突,直接將此元素置爲null;如果存在hash衝突,將這個數組的第一個元素設置爲當前Node的next指向的Node。
4.尋址
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
取出數組下標位置很重要,根據hash值計算。
存儲數據的要求,是否爲空,是否允許重複
允許爲空或者null,當key值爲空或null時,hash值默認0,計算出的數組下標爲0,也就是說key值爲null或者空串的,永遠在第一個位置,並用鏈表鏈接,key值不允許重複,value值允許重複,hash值允許重複。
存放與讀取是否有序
底層實現基於hash算法,無序。
是否線程安全
非線程安全,因爲所有方法都是不同步的,而且都是final,方法不能修改。