本文共 13916 字,大约阅读时间需要 46 分钟。
extends AbstractMapimplements Map , Cloneable, Serializable
// 单链表static class Nodeimplements Map.Entry { final int hash; 节点的hash值 final K key; key值 V value; value值 Node next; // 后置节点 Node(int hash, K key, V value, Node next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { // 由key和value的hashcode异或得到 return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { // 设置新值后返回旧值 V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry )o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始容量 16 static final int MAXIMUM_CAPACITY = 1 << 30;// 最大容量 2^30 static final float DEFAULT_LOAD_FACTOR = 0.75f;// 加载因子 public HashMap(int initialCapacity) { // 自定义初始容量的构造函数,在初始化HashMap的时候,应该尽量指定其大小。尤其是当你已知map中存放的元素个数时 this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { // 不带参数的构造函数 this.loadFactor = 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)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); } static final int tableSizeFor(int cap) { // 经过下面的 或 和位移 运算, n最终各位都是1。 int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
public void putAll(Map m) { putMapEntries(m, true); } // 将map的所有元素加入表中 final void putMapEntries(Map m, boolean evict) { int s = m.size(); if (s > 0) { if (table == null) { // pre-size // 重新计算阈值 float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); } else if (s > threshold) // 扩容 resize(); for (Map.Entry e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } }
final Node[] resize() { // 当前hashTab Node [] oldTab = table; // 当前桶的容量 int oldCap = (oldTab == null) ? 0 : oldTab.length; // 当前桶的阈值 int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { // 当前桶已经超出最大容量,不再扩容 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) // 2倍扩容 newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } 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"}) // 构建新的hash桶 Node [] newTab = (Node [])new Node[newCap]; table = newTab; if (oldTab != null) { // 遍历老的hash桶 for (int j = 0; j < oldCap; ++j) { Node e; if ((e = oldTab[j]) != null) { // 原来的node置空 以便GC oldTab[j] = null; if (e.next == null) // 位操作代替取模%,没有发生冲突 newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode)//如果发生过哈希碰撞,节点数小于8个。则要根据链表上每个节点的哈希值,依次放入新哈希桶对应下标位置。 ((TreeNode )e).split(this, newTab, j, oldCap); else { // preserve order// 扩容操作翻倍 原来的要么在index 要么index+oldLength Node loHead = null, loTail = null; Node hiHead = null, hiTail = null; Node next; do { next = e.next;// 取模看是否小于oldCap ==0 小于 oldCap index 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; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }// onlyIfAbsent if true, don't change existing value 表示这个值是true 不会覆盖相同key-value// boolean evict false表示初始时创建final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node[] tab; Node p; int n, i;// 为空则创建 扩容 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) // 没有发生冲突 构建新Node tab[i] = newNode(hash, key, value, null); else { Node e; K k;// hash值相同 key相同 覆盖value if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) // 红黑树 e = ((TreeNode )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; } } // 如果e不为空 找到要覆盖的节点 if (e != null) { // existing mapping for key V oldValue = e.value; // 覆盖并返回oldValue if (!onlyIfAbsent || oldValue == null) e.value = value;// 空实现 用作linkedHashMap afterNodeAccess(e); return oldValue; } } // 更新修改次数++ ++modCount; // 判断是否需要扩容 if (++size > threshold) resize(); //这是一个空实现的函数,用作LinkedHashMap重写使用。 afterNodeInsertion(evict); return null; }// 扰动函数 高位参与运算使得hash值更加均匀,减少hash碰撞概率static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
// 删除key-value对 返回valuepublic V remove(Object key) { Nodee; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; }final Node removeNode(int hash, Object key, Object value,boolean matchValue, boolean movable) { Node [] tab; Node p; int n, index; // 如果tab不为空 且根据hash找到节点有值 if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { // node为待删除节点 Node node = null, e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) // 删除节点引用赋值给node node = p; else if ((e = p.next) != null) { //否则循环遍历 找到待删除节点,赋值给node if (p instanceof TreeNode) node = ((TreeNode )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, 且 matchValue为false,或者值也相等 if (node != null && (!matchValue || (v = node.value) == value ||(value != null && value.equals(v)))) { if (node instanceof TreeNode) // 红黑树暂时不看 ((TreeNode )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; }
public V get(Object key) { Nodee; return (e = getNode(hash(key), key)) == null ? null : e.value; }final Node getNode(int hash, Object key) { Node [] tab; Node first, e; int n; K k;// 根据hash和key值找到node,找到返回value 否则 null 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 )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; }
public boolean containsKey(Object key) { return getNode(hash(key), key) != null; }final NodegetNode(int hash, Object key) { Node [] tab; Node 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 )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; }
public boolean containsValue(Object value) { Node[] tab; V v; 遍历hash桶 找到value 返回true if ((tab = table) != null && size > 0) { for (int i = 0; i < tab.length; ++i) { for (Node e = tab[i]; e != null; e = e.next) { if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false; }
@Override public V getOrDefault(Object key, V defaultValue) { Nodee; return (e = getNode(hash(key), key)) == null ? defaultValue : e.value; }
public HashSet() {map = new HashMap();}
转载地址:http://zhiii.baihongyu.com/