Last active
September 22, 2026 04:52
-
-
Save fantasticmao/9c088055dab10cdd1247e007bde6c7e5 to your computer and use it in GitHub Desktop.
Comments for Java Collections base on JDK8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package java.util; | |
| ...... | |
| public class ArrayList<E> extends AbstractList<E> | |
| implements List<E>, RandomAccess, Cloneable, java.io.Serializable | |
| { | |
| // 内部数组的默认容量 | |
| private static final int DEFAULT_CAPACITY = 10; | |
| // 空数组,当 size == 0 时使用 | |
| private static final Object[] EMPTY_ELEMENTDATA = {}; | |
| // 空数组,当 size == DEFAULT_CAPACITY 时使用 | |
| private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; | |
| // 内部数组,用于存放 ArrayList 元素 | |
| transient Object[] elementData; | |
| // 内部数组中的元素个数 | |
| private int size; | |
| // 记录链表的内部节点的改变次数 | |
| // 用于抛出 ConcurrentModificationException,为了避免同时迭代和修改内部数组 | |
| protected transient int modCount = 0; | |
| public ArrayList(int initialCapacity) { | |
| if (initialCapacity > 0) { | |
| // new 内部数组 | |
| this.elementData = new Object[initialCapacity]; | |
| } else if (initialCapacity == 0) { | |
| // 当 size == 0 时,替换内部数组为 EMPTY_ELEMENTDATA | |
| this.elementData = EMPTY_ELEMENTDATA; | |
| } else { | |
| throw new IllegalArgumentException("Illegal Capacity: "+ | |
| initialCapacity); | |
| } | |
| } | |
| public ArrayList() { | |
| this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; | |
| } | |
| public ArrayList(Collection<? extends E> c) { | |
| elementData = c.toArray(); | |
| if ((size = elementData.length) != 0) { | |
| // 兼容 c.toArray() 可能没有(不正确地)返回 Object[] 情况 | |
| if (elementData.getClass() != Object[].class) | |
| elementData = Arrays.copyOf(elementData, size, Object[].class); | |
| } else { | |
| // 当 size == 0 时,替换内部数组为 EMPTY_ELEMENTDATA | |
| this.elementData = EMPTY_ELEMENTDATA; | |
| } | |
| } | |
| // ArrayList 扩容操作 | |
| // 确认内部数组是否需要扩容 | |
| public void ensureCapacity(int minCapacity) { | |
| // 获当前取内部数组的容量 | |
| // 若当前内部数组不是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 时,则容量为 DEFAULT_CAPACITY | |
| int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) | |
| ? 0 : DEFAULT_CAPACITY; | |
| // 若当前内部数组的容量大于需要扩容的最小容量,则扩容内部数组 | |
| if (minCapacity > minExpand) { | |
| ensureExplicitCapacity(minCapacity); | |
| } | |
| } | |
| // 计算内部数组需要扩容的容量 | |
| private static int calculateCapacity(Object[] elementData, int minCapacity) { | |
| // 若当前内部数组是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 时,则选择 DEFAULT_CAPACITY 和 minCapacity 的最大值 | |
| if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { | |
| return Math.max(DEFAULT_CAPACITY, minCapacity); | |
| } | |
| return minCapacity; | |
| } | |
| private void ensureCapacityInternal(int minCapacity) { | |
| ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); | |
| } | |
| private void ensureExplicitCapacity(int minCapacity) { | |
| modCount++; | |
| if (minCapacity - elementData.length > 0) | |
| grow(minCapacity); | |
| } | |
| private void grow(int minCapacity) { | |
| // 新扩容的数组长度:旧数组长度 + 旧数组长度 / 2 | |
| int oldCapacity = elementData.length; | |
| int newCapacity = oldCapacity + (oldCapacity >> 1); | |
| if (newCapacity - minCapacity < 0) | |
| newCapacity = minCapacity; | |
| if (newCapacity - MAX_ARRAY_SIZE > 0) | |
| // 当新扩容的数组长度达到上限时,则以最大的内部数组长度扩容 | |
| newCapacity = hugeCapacity(minCapacity); | |
| elementData = Arrays.copyOf(elementData, newCapacity); | |
| } | |
| private static int hugeCapacity(int minCapacity) { | |
| if (minCapacity < 0) // overflow | |
| throw new OutOfMemoryError(); | |
| return (minCapacity > MAX_ARRAY_SIZE) ? | |
| Integer.MAX_VALUE : | |
| MAX_ARRAY_SIZE; | |
| } | |
| // ArrayList 数组操作 | |
| // 按升序判断元素在内部数组中的位置 | |
| public int indexOf(Object o) { | |
| if (o == null) { | |
| for (int i = 0; i < size; i++) | |
| if (elementData[i]==null) | |
| return i; | |
| } else { | |
| for (int i = 0; i < size; i++) | |
| if (o.equals(elementData[i])) | |
| return i; | |
| } | |
| return -1; | |
| } | |
| // 按降序判断元素在内部数组中的位置 | |
| public int lastIndexOf(Object o) { | |
| if (o == null) { | |
| for (int i = size-1; i >= 0; i--) | |
| if (elementData[i]==null) | |
| return i; | |
| } else { | |
| for (int i = size-1; i >= 0; i--) | |
| if (o.equals(elementData[i])) | |
| return i; | |
| } | |
| return -1; | |
| } | |
| // 按下标获取内部数组的元素 | |
| @SuppressWarnings("unchecked") | |
| E elementData(int index) { | |
| return (E) elementData[index]; | |
| } | |
| // 按下标设置内部数组的元素,并返回旧元素值 | |
| public E get(int index) { | |
| // 校验参数 | |
| rangeCheck(index); | |
| return elementData(index); | |
| } | |
| // 按下标设置内部数组的元素,并返回旧元素值 | |
| public E set(int index, E element) { | |
| //校验参数 | |
| rangeCheck(index); | |
| E oldValue = elementData(index); | |
| elementData[index] = element; | |
| return oldValue; | |
| } | |
| // 添加新元素至内部数组的末尾位置 | |
| public boolean add(E e) { | |
| // 确认内部数组是否需要扩容 | |
| ensureCapacityInternal(size + 1); // Increments modCount!! | |
| elementData[size++] = e; | |
| return true; | |
| } | |
| // 添加新元素至内部数组的指定下标位置 | |
| public void add(int index, E element) { | |
| // 校验参数 | |
| rangeCheckForAdd(index); | |
| // 确认内部数组是否需要扩容 | |
| ensureCapacityInternal(size + 1); // Increments modCount!! | |
| // 将内部数组 index 之后的元素向后移动一位 | |
| System.arraycopy(elementData, index, elementData, index + 1, | |
| size - index); | |
| // 将新元素复制给内部数组的 index 下标位置 | |
| elementData[index] = element; | |
| // 更新 size | |
| size++; | |
| } | |
| // 按下标删除内部数组的元素,并返回旧元素值 | |
| public E remove(int index) { | |
| // 校验参数 | |
| rangeCheck(index); | |
| modCount++; | |
| E oldValue = elementData(index); | |
| // 将内部数组 index 之后的元素向前移动一位 | |
| int numMoved = size - index - 1; | |
| if (numMoved > 0) | |
| System.arraycopy(elementData, index+1, elementData, index, | |
| numMoved); | |
| // 将数组最后一位元素置空 | |
| elementData[--size] = null; // clear to let GC do its work | |
| return oldValue; | |
| } | |
| // 按 o.equals() 匹配并删除内部数组的元素,并返回删除是否成功 | |
| public boolean remove(Object o) { | |
| if (o == null) { | |
| for (int index = 0; index < size; index++) | |
| if (elementData[index] == null) { | |
| fastRemove(index); | |
| return true; | |
| } | |
| } else { | |
| for (int index = 0; index < size; index++) | |
| if (o.equals(elementData[index])) { | |
| fastRemove(index); | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| // 移动内部数组 | |
| private void fastRemove(int index) { | |
| modCount++; | |
| // 将内部数组 index 之后的元素向前移动一位 | |
| int numMoved = size - index - 1; | |
| if (numMoved > 0) | |
| System.arraycopy(elementData, index+1, elementData, index, | |
| numMoved); | |
| // 将数组最后一位元素置空 | |
| elementData[--size] = null; // clear to let GC do its work | |
| } | |
| // 集合的差集:删除内部数组中的指定元素 | |
| public boolean removeAll(Collection<?> c) { | |
| Objects.requireNonNull(c); | |
| return batchRemove(c, false); | |
| } | |
| // 集合的交集:检索内部数组中的指定元素 | |
| public boolean retainAll(Collection<?> c) { | |
| Objects.requireNonNull(c); | |
| return batchRemove(c, true); | |
| } | |
| private boolean batchRemove(Collection<?> c, boolean complement) { | |
| final Object[] elementData = this.elementData; | |
| int r = 0, w = 0; | |
| boolean modified = false; | |
| try { | |
| for (; r < size; r++) | |
| // removeAll:将未匹配的元素保留下来 | |
| // retainAll:将匹配的元素保留下来 | |
| if (c.contains(elementData[r]) == complement) | |
| elementData[w++] = elementData[r]; | |
| } finally { | |
| // Preserve behavioral compatibility with AbstractCollection, | |
| // even if c.contains() throws. | |
| if (r != size) { | |
| System.arraycopy(elementData, r, | |
| elementData, w, | |
| size - r); | |
| w += size - r; | |
| } | |
| if (w != size) { | |
| // clear to let GC do its work | |
| for (int i = w; i < size; i++) | |
| elementData[i] = null; | |
| modCount += size - w; | |
| size = w; | |
| modified = true; | |
| } | |
| } | |
| return modified; | |
| } | |
| ...... | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package java.util; | |
| ...... | |
| public class HashMap<K,V> extends AbstractMap<K,V> | |
| implements Map<K,V>, Cloneable, Serializable { | |
| // Node 数组的默认容量 | |
| static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; | |
| // Node 数组的最大容量 | |
| static final int MAXIMUM_CAPACITY = 1 << 30; | |
| // Node 数组的加载因子 | |
| static final float DEFAULT_LOAD_FACTOR = 0.75f; | |
| // Node 节点由 LinkedList 转换为 Tree 的临界值 | |
| static final int TREEIFY_THRESHOLD = 8; | |
| // Node 节点由 Tree 转换为 LinkedList 的临界值 | |
| static final int UNTREEIFY_THRESHOLD = 6; | |
| // Node 节点由 LinkedList 转换为 Tree 时,Node 数组的最小容量 | |
| static final int MIN_TREEIFY_CAPACITY = 64; | |
| // HashMap 内部节点,实现 Map.Entry 接口,用于存放 HashMap 的 Key-Value 数据 | |
| 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; | |
| } | |
| public final int hashCode() { | |
| // 计算 Node 节点的 hashCode | |
| return Objects.hashCode(key) ^ Objects.hashCode(value); | |
| } | |
| ...... | |
| } | |
| // 计算 Key 的 hashCode | |
| static final int hash(Object key) { | |
| int h; | |
| // 1. h1 = key.hashCode() | |
| // 2. h2 = key.hashCode() >>> 16 | |
| // 3. h1 ^ h2 | |
| return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); | |
| } | |
| ...... | |
| // Node 数组,每个 Node 节点可能为 LinkedList 或 Tree,两者之间可以互相转换 | |
| transient Node<K,V>[] table; | |
| // 冗余字段,由 keySet() 和 values() 调用 | |
| transient Set<Map.Entry<K,V>> entrySet; | |
| // 冗余字段,统计 HashMap 内部的 Node 节点的个数 | |
| // 当 size > threshold 时,Node 数组将会调用 resize() 扩容 | |
| transient int size; | |
| // 冗余字段,用于抛出 ConcurrentModificationException,为了避免同时迭代和修改 Node 数组 | |
| transient int modCount; | |
| // Node 数组的扩容阈值,threshold = capacity * loadFactor | |
| int threshold; | |
| // Node 数组的加载因子 | |
| final float loadFactor; | |
| public HashMap(int initialCapacity, float loadFactor) { | |
| ...... | |
| } | |
| public HashMap(int initialCapacity) { | |
| ...... | |
| } | |
| public HashMap() { | |
| ...... | |
| } | |
| ...... | |
| // 根据 Key 获取 Value | |
| public V get(Object key) { | |
| Node<K,V> e; | |
| // HashMap 允许 Key 为 null | |
| return (e = getNode(hash(key), key)) == null ? null : e.value; | |
| } | |
| // 根据 Key 的 hashCode,从 Node 数组中获取 Node 节点 | |
| 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 && | |
| // 存储在 Node 数组中的索引值为 (table.lenth - 1) & hashCode | |
| (first = tab[(n - 1) & hash]) != null) { | |
| // 判断 Key 是否匹配的条件:Node的哈希值相等 && key的引用相等 || key的equals()执行成功 | |
| 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) | |
| // 当 Node 节点是 Tree | |
| return ((TreeNode<K,V>)first).getTreeNode(hash, key); | |
| do { | |
| // 当 Node 节点是 LinkedList | |
| if (e.hash == hash && | |
| ((k = e.key) == key || (key != null && key.equals(k)))) | |
| return e; | |
| } while ((e = e.next) != null); | |
| } | |
| } | |
| return null; | |
| } | |
| // 判断 Key 是否存在 | |
| public boolean containsKey(Object key) { | |
| // 根据 Key 获取 Node 节点不为 null | |
| return getNode(hash(key), key) != null; | |
| } | |
| // 向 Node 数组添加 Key-Value 键值对 | |
| public V put(K key, V value) { | |
| return putVal(hash(key), key, value, false, true); | |
| } | |
| // 根据 Key 的 hashCode,向 Node 数组添加 Key-Value 键值对 | |
| 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) | |
| // 初始化 Node 数组 | |
| n = (tab = resize()).length; | |
| // 存储在 Node 数组中的索引值为 (table.lenth - 1) & hashCode | |
| if ((p = tab[i = (n - 1) & hash]) == null) | |
| // 若 Node 节点不存在,则创建节点 | |
| tab[i] = newNode(hash, key, value, null); | |
| else { | |
| Node<K,V> e; K k; | |
| // 判断 Key 是否匹配的条件:Node的哈希值相等 && key的引用相等 || key的equals()执行成功 | |
| if (p.hash == hash && | |
| ((k = p.key) == key || (key != null && key.equals(k)))) | |
| // 替换 Node 节点 | |
| e = p; | |
| else if (p instanceof TreeNode) | |
| // 当 Node 节点是 Tree | |
| e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); | |
| else { | |
| // 当 Node 节点是 LinkedList | |
| for (int binCount = 0; ; ++binCount) { | |
| if ((e = p.next) == null) { | |
| p.next = newNode(hash, key, value, null); | |
| // 当 LinkedList 深度 >= TREEIFY_THRESHOLD - 1,则将 LinkedList 转置为 Tree | |
| if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st | |
| treeifyBin(tab, hash); | |
| break; | |
| } | |
| // 遍历 LinkedList 获取 Node 节点 | |
| 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; | |
| // 当 Value == null 的情况下赋值 | |
| if (!onlyIfAbsent || oldValue == null) | |
| e.value = value; | |
| afterNodeAccess(e); | |
| return oldValue; | |
| } | |
| } | |
| // 记录修改一次 Node 数组 | |
| ++modCount; | |
| // 当 size > threshold 时,扩容 Node 数组 | |
| if (++size > threshold) | |
| resize(); | |
| afterNodeInsertion(evict); | |
| return null; | |
| } | |
| final Node<K,V>[] resize() { | |
| Node<K,V>[] 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; | |
| } | |
| // Node 数组的新容量为旧容量 * 2 | |
| else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && | |
| oldCap >= DEFAULT_INITIAL_CAPACITY) | |
| // Node 数组的扩容阈值 * 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"}) | |
| // 创建新的 Node 数组,容量为旧数组的两倍 | |
| Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; | |
| table = newTab; | |
| if (oldTab != null) { | |
| // 迁移数据,并保证节点顺序 | |
| for (int j = 0; j < oldCap; ++j) { | |
| Node<K,V> e; | |
| if ((e = oldTab[j]) != null) { | |
| oldTab[j] = null; | |
| if (e.next == null) | |
| // 当 Node 节点是根节点 | |
| newTab[e.hash & (newCap - 1)] = e; | |
| else if (e instanceof TreeNode) | |
| // 当 Node 节点是 Tree | |
| ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); | |
| else { // preserve order | |
| // 当 Node 节点是 LinkedList | |
| Node<K,V> loHead = null, loTail = null; | |
| Node<K,V> hiHead = null, hiTail = null; | |
| Node<K,V> next; | |
| do { | |
| next = e.next; | |
| // 此处设计非常巧妙 | |
| // 根据 Key.hashCode & oldCap == 0,来区分迁移数据 | |
| 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); | |
| // 1. 若 Key.hashCode & oldCap == 0,则新 Node 节点在新数组中的索引为原索引 | |
| // 2. 若 Key.hashCode & oldCap != 0,则新 Node 节点在新数组中的索引为原索引 + 旧数组容量(即原索引 * 2) | |
| if (loTail != null) { | |
| loTail.next = null; | |
| newTab[j] = loHead; | |
| } | |
| if (hiTail != null) { | |
| hiTail.next = null; | |
| newTab[j + oldCap] = hiHead; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| return newTab; | |
| } | |
| // 根据 Key 删除 Value | |
| public V remove(Object key) { | |
| Node<K,V> e; | |
| return (e = removeNode(hash(key), key, null, false, true)) == null ? | |
| null : e.value; | |
| } | |
| // 根据 Key 的 hashCode,向 Node 数组删除 Key-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; | |
| 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; | |
| // 获取 Key 对应的 Node 节点 | |
| 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.next = node.next; | |
| ++modCount; | |
| --size; | |
| afterNodeRemoval(node); | |
| return node; | |
| } | |
| } | |
| return null; | |
| } | |
| // 清空 Node 数组 | |
| public void clear() { | |
| Node<K,V>[] tab; | |
| modCount++; | |
| if ((tab = table) != null && size > 0) { | |
| size = 0; | |
| for (int i = 0; i < tab.length; ++i) | |
| tab[i] = null; | |
| } | |
| } | |
| // 判断 Value 是否存在 | |
| public boolean containsValue(Object value) { | |
| Node<K,V>[] tab; V v; | |
| if ((tab = table) != null && size > 0) { | |
| for (int i = 0; i < tab.length; ++i) { | |
| // 遍历 Node 节点 | |
| for (Node<K,V> e = tab[i]; e != null; e = e.next) { | |
| if ((v = e.value) == value || | |
| (value != null && value.equals(v))) | |
| return true; | |
| } | |
| } | |
| } | |
| return false; | |
| } | |
| ...... | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package java.util; | |
| ...... | |
| public class Hashtable<K,V> | |
| extends Dictionary<K,V> | |
| implements Map<K,V>, Cloneable, java.io.Serializable { | |
| // Entry 数组,每个 Entry 节点都是一个 LinkedList | |
| private transient Entry<?,?>[] table; | |
| // 冗余字段,统计 HashTable 内部的 Entry 节点个数 | |
| private transient int count; | |
| // Entry 数组的扩容阈值,threshold = capacity * loadFactor | |
| private int threshold; | |
| // Entry 数组的加载因子 | |
| private float loadFactor; | |
| // 冗余字段,用于抛出 ConcurrentModificationException,为了避免同时迭代和修改 Node 数组 | |
| private transient int modCount = 0; | |
| public Hashtable(int initialCapacity, float loadFactor) { | |
| ...... | |
| } | |
| public Hashtable(int initialCapacity) { | |
| ...... | |
| } | |
| public Hashtable() { | |
| ...... | |
| } | |
| ...... | |
| // 同步根据 Key 获取 Value | |
| @SuppressWarnings("unchecked") | |
| public synchronized V get(Object key) { | |
| Entry<?,?> tab[] = table; | |
| // 计算 Key 的 hashCode | |
| int hash = key.hashCode(); | |
| // 存储在 Entry 数组中的索引值为 (hashCode & 0x7FFFFFFF) % table.length | |
| int index = (hash & 0x7FFFFFFF) % tab.length; | |
| // 遍历 Entry 节点,Node 节点不为 null | |
| for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { | |
| // 判断 Key 是否匹配的条件:Entry的哈希值相等 && Key的equals()执行成功 | |
| if ((e.hash == hash) && e.key.equals(key)) { | |
| return (V)e.value; | |
| } | |
| } | |
| return null; | |
| } | |
| // 同步向 Entry 数组添加 Key-Value 键值对 | |
| public synchronized V put(K key, V value) { | |
| if (value == null) { | |
| // Node 节点不为 null | |
| throw new NullPointerException(); | |
| } | |
| Entry<?,?> tab[] = table; | |
| int hash = key.hashCode(); | |
| // 存储在 Entry 数组中的索引值为 (hashCode & 0x7FFFFFFF) % table.length | |
| int index = (hash & 0x7FFFFFFF) % tab.length; | |
| @SuppressWarnings("unchecked") | |
| Entry<K,V> entry = (Entry<K,V>)tab[index]; | |
| for(; entry != null ; entry = entry.next) { | |
| // 判断 Key 是否匹配的条件:Entry的哈希值相等 && Key的equals()执行成功 | |
| if ((entry.hash == hash) && entry.key.equals(key)) { | |
| V old = entry.value; | |
| // 替换 Entry 节点 | |
| entry.value = value; | |
| return old; | |
| } | |
| } | |
| addEntry(hash, key, value, index); | |
| return null; | |
| } | |
| // 根据 Key 的 hashCode,同步向 Entry 数组添加 Key-Value 键值对 | |
| private void addEntry(int hash, K key, V value, int index) { | |
| // 记录修改一次 Entry 数组 | |
| modCount++; | |
| Entry<?,?> tab[] = table; | |
| if (count >= threshold) { | |
| // 当 count >= threshold 时,扩容 Entry 数组 | |
| rehash(); | |
| tab = table; | |
| hash = key.hashCode(); | |
| // 存储在 Entry 数组中的索引值为 (hashCode & 0x7FFFFFFF) % table.length | |
| index = (hash & 0x7FFFFFFF) % tab.length; | |
| } | |
| @SuppressWarnings("unchecked") | |
| Entry<K,V> e = (Entry<K,V>) tab[index]; | |
| // 创建新的 Entry 节点,并链接旧 Entry 节点 | |
| tab[index] = new Entry<>(hash, key, value, e); | |
| count++; | |
| } | |
| @SuppressWarnings("unchecked") | |
| protected void rehash() { | |
| int oldCapacity = table.length; | |
| Entry<?,?>[] oldMap = table; | |
| // 新 Entry 数组的容量为 (旧容量 * 2) + 1 | |
| int newCapacity = (oldCapacity << 1) + 1; | |
| // 当新 Entry 数组的容量大于 Entry 数组的最大容量,则保持运行最大容量的 Entry 数组 | |
| if (newCapacity - MAX_ARRAY_SIZE > 0) { | |
| if (oldCapacity == MAX_ARRAY_SIZE) | |
| return; | |
| newCapacity = MAX_ARRAY_SIZE; | |
| } | |
| Entry<?,?>[] newMap = new Entry<?,?>[newCapacity]; | |
| // 记录修改一次 Entry 数组 | |
| modCount++; | |
| // 兼容 Entry 数组最大容量的情况 | |
| threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1); | |
| table = newMap; | |
| // 迁移数据 | |
| for (int i = oldCapacity ; i-- > 0 ;) { | |
| for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) { | |
| Entry<K,V> e = old; | |
| old = old.next; | |
| int index = (e.hash & 0x7FFFFFFF) % newCapacity; | |
| e.next = (Entry<K,V>)newMap[index]; | |
| newMap[index] = e; | |
| } | |
| } | |
| } | |
| ...... | |
| private static class Entry<K,V> implements Map.Entry<K,V> { | |
| final int hash; | |
| final K key; | |
| V value; | |
| Entry<K,V> next; | |
| protected Entry(int hash, K key, V value, Entry<K,V> next) { | |
| this.hash = hash; | |
| this.key = key; | |
| this.value = value; | |
| this.next = next; | |
| } | |
| public int hashCode() { | |
| // 计算 Entry 节点的 hashcode | |
| return hash ^ Objects.hashCode(value); | |
| } | |
| ...... | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package java.util; | |
| ...... | |
| // LinkedHashMap 类继承自 HashMap | |
| public class LinkedHashMap<K,V> | |
| extends HashMap<K,V> | |
| implements Map<K,V> | |
| { | |
| // LinkedHashMap 内部节点,继承 HashMap.Node 类 | |
| static class Entry<K,V> extends HashMap.Node<K,V> { | |
| // 增加 before 和 after 字段,用于记录 Entry 节点在双向链表中的上一个节点和下一个节点 | |
| Entry<K,V> before, after; | |
| Entry(int hash, K key, V value, Node<K,V> next) { | |
| super(hash, key, value, next); | |
| } | |
| } | |
| // Entry 节点,记录 LinkedHashMap 双向链表的第一个节点(也是 eldest 节点) | |
| transient LinkedHashMap.Entry<K,V> head; | |
| // Entry 节点,记录 LinkedHashMap 双向链表的最后一个节点(也是 youngest 节点) | |
| transient LinkedHashMap.Entry<K,V> tail; | |
| // 定义遍历 LinkedHashMap 内部节点的排序方式 | |
| final boolean accessOrder; | |
| // 将新生成的 Entry 节点关联到 LinkedHashMap 双向链表中 | |
| private void linkNodeLast(LinkedHashMap.Entry<K,V> p) { | |
| // 在添加新的 Entry 节点之前,保存 LinkedHashMap 双向链表的「最后一个节点」为局部变量 last | |
| // last 局部变量表示在添加新的 Entry 节点之后,LinkedHashMap 双向链表的「上一个最后一个节点」 | |
| LinkedHashMap.Entry<K,V> last = tail; | |
| // 开始添加新的 Entry 节点至 LinkedHashMap 双向链表 | |
| // 将 LinkedHashMap 双向链表的「最后一个节点」赋值为新添加的 Entry 节点 | |
| tail = p; | |
| if (last == null) | |
| // 若 LinkedHashMap 双向链表的「上一个最后一个节点」不存在,则表示双向链表为空 | |
| // 并将双向链表的「第一个节点」也赋值为新添加的 Entry 节点 | |
| head = p; | |
| else { | |
| // 若 LinkedHashMap 双向链表的「上一个最后一个节点」存在,则表示双向链表不为空 | |
| // 并将新添加的 Entry 节点的「上一个节点」链接到双向链表的「上一个最后一个节点」 | |
| // 并将双向链表的「上一个最后一个节点」的「下一个节点」链接到新添加的 Entry 节点 | |
| p.before = last; | |
| last.after = p; | |
| } | |
| } | |
| // 将源 Entry 节点替换为目标 Entry 节点,并更新 LinkedHashMap 双向链表 | |
| private void transferLinks(LinkedHashMap.Entry<K,V> src, | |
| LinkedHashMap.Entry<K,V> dst) { | |
| LinkedHashMap.Entry<K,V> b = dst.before = src.before; | |
| LinkedHashMap.Entry<K,V> a = dst.after = src.after; | |
| if (b == null) | |
| head = dst; | |
| else | |
| b.after = dst; | |
| if (a == null) | |
| tail = dst; | |
| else | |
| a.before = dst; | |
| } | |
| // 重新初始化 LinkedHashMap | |
| void reinitialize() { | |
| super.reinitialize(); | |
| // 将 LinkedHashMap 双向链表也置空 | |
| head = tail = null; | |
| } | |
| // 重写 newNode(int, K, V, Node<K, V>) | |
| Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) { | |
| LinkedHashMap.Entry<K,V> p = | |
| new LinkedHashMap.Entry<K,V>(hash, key, value, e); | |
| // 将新生成的 Entry 节点关联到 LinkedHashMap 双向链表中 | |
| linkNodeLast(p); | |
| return p; | |
| } | |
| // 重写 replacementNode(Node<K, V>, Node<K, V>) | |
| Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) { | |
| LinkedHashMap.Entry<K,V> q = (LinkedHashMap.Entry<K,V>)p; | |
| LinkedHashMap.Entry<K,V> t = | |
| new LinkedHashMap.Entry<K,V>(q.hash, q.key, q.value, next); | |
| // 将需替换的 Entry 节点关联到 LinkedHashMap 双向链表中 | |
| transferLinks(q, t); | |
| return t; | |
| } | |
| // 重写 newTreeNode(int, K, V, Node<K, V>) | |
| TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) { | |
| TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next); | |
| // 将新生成的 Entry 节点关联到 LinkedHashMap 双向链表中 | |
| linkNodeLast(p); | |
| return p; | |
| } | |
| // 重写 replacementTreeNode(Node<K, V>, Node<K, V>) | |
| TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) { | |
| LinkedHashMap.Entry<K,V> q = (LinkedHashMap.Entry<K,V>)p; | |
| TreeNode<K,V> t = new TreeNode<K,V>(q.hash, q.key, q.value, next); | |
| // 将需替换的 Entry 节点关联到 LinkedHashMap 双向链表中 | |
| transferLinks(q, t); | |
| return t; | |
| } | |
| // 删除 HashMap.Node 节点时,更新 LinkedHashMap 双向链表 | |
| void afterNodeRemoval(Node<K,V> e) { // unlink | |
| LinkedHashMap.Entry<K,V> p = | |
| (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; | |
| p.before = p.after = null; | |
| if (b == null) | |
| head = a; | |
| else | |
| b.after = a; | |
| if (a == null) | |
| tail = b; | |
| else | |
| a.before = b; | |
| } | |
| // 插入 HashMap.Node 节点时,更新 LinkedHashMap 双向链表 | |
| void afterNodeInsertion(boolean evict) { // possibly remove eldest | |
| LinkedHashMap.Entry<K,V> first; | |
| // 若需要在插入节点时,删除 LinkedHashMap 双向链表的 eldest 节点,可以通过重写 removeEldestEntry(Map.Entry<K, V>) 并返回结果 true 实现 | |
| if (evict && (first = head) != null && removeEldestEntry(first)) { | |
| K key = first.key; | |
| removeNode(hash(key), key, null, false, true); | |
| } | |
| } | |
| // 若 LinkedHashMap 内部按访问顺序排序,则在获取 HashMap.Node 时,更新 LinkedHashMap 双向链表 | |
| void afterNodeAccess(Node<K,V> e) { // move node to last | |
| LinkedHashMap.Entry<K,V> last; | |
| if (accessOrder && (last = tail) != e) { | |
| LinkedHashMap.Entry<K,V> p = | |
| (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; | |
| p.after = null; | |
| if (b == null) | |
| head = a; | |
| else | |
| b.after = a; | |
| if (a != null) | |
| a.before = b; | |
| else | |
| last = b; | |
| if (last == null) | |
| head = p; | |
| else { | |
| p.before = last; | |
| last.after = p; | |
| } | |
| tail = p; | |
| ++modCount; | |
| } | |
| } | |
| public LinkedHashMap(int initialCapacity, float loadFactor) { | |
| super(initialCapacity, loadFactor); | |
| accessOrder = false; | |
| } | |
| public LinkedHashMap(int initialCapacity) { | |
| super(initialCapacity); | |
| accessOrder = false; | |
| } | |
| public LinkedHashMap() { | |
| super(); | |
| accessOrder = false; | |
| } | |
| public LinkedHashMap(Map<? extends K, ? extends V> m) { | |
| super(); | |
| accessOrder = false; | |
| putMapEntries(m, false); | |
| } | |
| public LinkedHashMap(int initialCapacity, | |
| float loadFactor, | |
| boolean accessOrder) { | |
| super(initialCapacity, loadFactor); | |
| // 指定 LinkedHashMap 内部排序方式:true 访问顺序,false 插入顺序 | |
| this.accessOrder = accessOrder; | |
| } | |
| // 重写 containsValue(Object),从 LinkedHashMap 双向链表的第一个节点开始遍历,判断 Value 是否存在 | |
| public boolean containsValue(Object value) { | |
| for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) { | |
| V v = e.value; | |
| if (v == value || (value != null && value.equals(v))) | |
| return true; | |
| } | |
| return false; | |
| } | |
| // 重写 get(Object),根据 Key 获取 Value | |
| public V get(Object key) { | |
| Node<K,V> e; | |
| // 使用 HashMap.getNode(int, Object) 获取节点 | |
| if ((e = getNode(hash(key), key)) == null) | |
| // LinkedHashMap 允许 Key 为 null | |
| return null; | |
| if (accessOrder) | |
| afterNodeAccess(e); | |
| return e.value; | |
| } | |
| // LinkedHashMap 没有重写 put(K, V) | |
| ...... | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package java.util; | |
| ...... | |
| public class LinkedList<E> | |
| extends AbstractSequentialList<E> | |
| implements List<E>, Deque<E>, Cloneable, java.io.Serializable | |
| { | |
| // 链表中的节点个数 | |
| transient int size = 0; | |
| // 链表中的第一个节点 | |
| transient Node<E> first; | |
| // 链表中的最后一个节点 | |
| transient Node<E> last; | |
| // 记录链表的内部节点的改变次数 | |
| // 用于抛出 ConcurrentModificationException,为了避免同时迭代和修改内部数组 | |
| protected transient int modCount = 0 | |
| // LinkedList 内部节点,用于存放 LinkedList 的 <E> 数据 | |
| private static class Node<E> { | |
| // 内部节点的数据 | |
| E item; | |
| // 内部节点的上一个节点 | |
| Node<E> next; | |
| // 内部节点的下一个节点 | |
| Node<E> prev; | |
| Node(Node<E> prev, E element, Node<E> next) { | |
| this.item = element; | |
| this.next = next; | |
| this.prev = prev; | |
| } | |
| } | |
| public LinkedList() { | |
| } | |
| public LinkedList(Collection<? extends E> c) { | |
| this(); | |
| addAll(c); | |
| } | |
| // 将元素关联为链表的第一个节点 | |
| private void linkFirst(E e) { | |
| final Node<E> f = first; | |
| // 创建一个新的节点,作为第一个节点 | |
| final Node<E> newNode = new Node<>(null, e, f); | |
| first = newNode; | |
| if (f == null) | |
| last = newNode; | |
| else | |
| f.prev = newNode; | |
| size++; | |
| modCount++; | |
| } | |
| // 将元素关联为链表的最后一个节点 | |
| void linkLast(E e) { | |
| final Node<E> l = last; | |
| // 创建一个新的节点,作为最后一个节点 | |
| final Node<E> newNode = new Node<>(l, e, null); | |
| last = newNode; | |
| if (l == null) | |
| first = newNode; | |
| else | |
| l.next = newNode; | |
| size++; | |
| modCount++; | |
| } | |
| // 将元素关联为指定节点的上一个节点 | |
| void linkBefore(E e, Node<E> succ) { | |
| // 获取指定节点的上一个节点 | |
| final Node<E> pred = succ.prev; | |
| // 创建一个新的节点,prev = 指定节点的上一个节点,next = 指定节点 | |
| final Node<E> newNode = new Node<>(pred, e, succ); | |
| // 修改指定节点的上一个节点 | |
| succ.prev = newNode; | |
| if (pred == null) | |
| first = newNode; | |
| else | |
| pred.next = newNode; | |
| size++; | |
| modCount++; | |
| } | |
| // 从链表中删除第一个节点,并返回第一个节点的数据 | |
| private E unlinkFirst(Node<E> f) { | |
| final E element = f.item; | |
| final Node<E> next = f.next; | |
| f.item = null; | |
| f.next = null; // help GC | |
| first = next; | |
| if (next == null) | |
| last = null; | |
| else | |
| next.prev = null; | |
| size--; | |
| modCount++; | |
| return element; | |
| } | |
| // 从链表中删除最后一个节点,并返回最后一个节点的数据 | |
| private E unlinkLast(Node<E> l) { | |
| // assert l == last && l != null; | |
| final E element = l.item; | |
| final Node<E> prev = l.prev; | |
| l.item = null; | |
| l.prev = null; // help GC | |
| last = prev; | |
| if (prev == null) | |
| first = null; | |
| else | |
| prev.next = null; | |
| size--; | |
| modCount++; | |
| return element; | |
| } | |
| // 从链表中删除指定节点,并返回指定节点的数据 | |
| E unlink(Node<E> x) { | |
| final E element = x.item; | |
| final Node<E> next = x.next; | |
| final Node<E> prev = x.prev; | |
| if (prev == null) { | |
| first = next; | |
| } else { | |
| prev.next = next; | |
| x.prev = null; | |
| } | |
| if (next == null) { | |
| last = prev; | |
| } else { | |
| next.prev = prev; | |
| x.next = null; | |
| } | |
| x.item = null; | |
| size--; | |
| modCount++; | |
| return element; | |
| } | |
| // 获取链表的第一个节点 | |
| public E getFirst() { | |
| final Node<E> f = first; | |
| if (f == null) | |
| throw new NoSuchElementException(); | |
| return f.item; | |
| } | |
| // 获取链表的最后一个节点 | |
| public E getLast() { | |
| final Node<E> l = last; | |
| if (l == null) | |
| throw new NoSuchElementException(); | |
| return l.item; | |
| } | |
| // 删除链表的第一个节点 | |
| public E removeFirst() { | |
| final Node<E> f = first; | |
| if (f == null) | |
| throw new NoSuchElementException(); | |
| return unlinkFirst(f); | |
| } | |
| // 删除链表的最后一个节点 | |
| public E removeLast() { | |
| final Node<E> l = last; | |
| if (l == null) | |
| throw new NoSuchElementException(); | |
| return unlinkLast(l); | |
| } | |
| // 添加一个节点至链表的开头 | |
| public void addFirst(E e) { | |
| linkFirst(e); | |
| } | |
| // 添加一个节点至链表的末尾 | |
| public void addLast(E e) { | |
| linkLast(e); | |
| } | |
| ...... | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment