深入理解Java集合框架

客官°小女子只卖身不卖艺 2021-09-22 00:20 553阅读 0赞

Java集合实现了常用数据结构,是开发中最常用的功能之一。

Java集合主要的功能由三个接口:List、Set、Queue以及Collection组成。

常见接口:

  • List : 列表,顺序存储,可重复
  • Set :集合,与数学中的集合有同样的特性:元素不能重复
  • Queue:队列
  • Collection:所有Java集合的接口,定义了“集合”的常用接口

结构结构

数据结构

常用集合

  • ArrayList 一种可以动态增长或缩减的索引集合,底层通过Ojbect[]数组实现,默认容量为10,在使用是如果确定仓储的数据容量应尽量为其初始化以避免动态扩容时的拷贝开销
  • LinkedList 高效插入删除的有序序列,是双向链表,使用node节点存储数据;它又实现了双向队列
  • ArrayDeque 用循环数组实现的双端队列
  • HashSet 一种没有元素的无序集合
  • TreeSet 有序的集合
  • LinkedHashSet 能记录插入顺序的集合
  • PriorityQueue 优先队列
  • HashMap 存储键/值关系数据
  • TreeMap 能根据键的值排序的键/值关系数据数据
  • LinkedHashMap 可以键/值记录添加顺序

Java集合框架结构

Java集合Collection.png

如何选用这些数据结构

通常选用基于我们需要处理的数据的特点以及集合的特点来确定的。

如果只是简单存储一组数据,如几个用户的信息,这时选用ArrayList是比较合适的,如果数据频繁添加、删除那选用LinkedList是比较合适的。

如果想存储一组数据且不希望重复,那选用Set集合合适的。

如果希望添加插入的数据能够有顺序,那选择TreeSet是比较合适的,当然TreeMap也可以。

使用

ArrayList

  1. import org.junit.Test;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.Collections;
  5. import java.util.List;
  6. public class ArrayListTest {
  7. @Test
  8. public void test() throws Exception {
  9. ArrayList<Integer> list = new ArrayList<>();
  10. // 更推荐使用面向接口的使用方式,方便以后切换
  11. //List<Integer> list = new ArrayList<>();
  12. list.add(3);
  13. list.add(2);
  14. list.add(1);
  15. // for打印
  16. for (Integer e : list) {
  17. System.out.println(e);
  18. }
  19. // 排序 小->大
  20. Collections.sort(list);
  21. System.out.println(list); // 打印
  22. // 排序 大->小
  23. List<Integer> list2 = Arrays.asList(2,3,5);
  24. Collections.sort(list2,(a,b)->b-a);
  25. // 排序 大->小
  26. list2.sort((a, b) -> b - a); // 功能同上
  27. System.out.println(list2);
  28. }
  29. }
  30. // 输出
  31. 3
  32. 2
  33. 1
  34. [1, 2, 3]
  35. [5, 3, 2]

Set

  1. import org.junit.Test;
  2. import java.util.HashSet;
  3. import java.util.Objects;
  4. import java.util.Set;
  5. public class SetTest {
  6. static class User {
  7. String name;
  8. int age;
  9. public User(String name, int age) {
  10. this.name = name;
  11. this.age = age;
  12. }
  13. @Override
  14. public int hashCode() {
  15. return Objects.hashCode(this.name);
  16. }
  17. // 逻辑根据名字判断User是否相同
  18. @Override
  19. public boolean equals(Object obj) {
  20. if (obj == null) return false;
  21. if (obj instanceof User) {
  22. User u = (User) obj;
  23. return this.name != null
  24. ? this.name.equals(u.name)
  25. : u.name == null;
  26. }
  27. return false;
  28. }
  29. @Override
  30. public String toString() {
  31. return "User{" +
  32. "name='" + name + '\'' +
  33. ", age=" + age +
  34. '}';
  35. }
  36. }
  37. @Test
  38. public void test() throws Exception {
  39. Set<Integer> set = new HashSet<>();
  40. set.add(1);
  41. set.add(2);
  42. set.add(3);
  43. set.add(3);
  44. System.out.println(set);
  45. // 添加重复的人
  46. Set<User> users = new HashSet<>();
  47. users.add(new User("张三",18));
  48. // 重复,不进行添加
  49. users.add(new User("张三",19));
  50. users.add(new User("李四",20));
  51. for (User u : users) {
  52. System.out.println(u);
  53. }
  54. }
  55. }
  56. // 输出
  57. [1, 2, 3]
  58. User{ name='null', age=18}
  59. User{ name='李四', age=20}

HashMap

  1. import org.junit.Test;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class HashMapTest {
  5. @Test
  6. public void test() throws Exception {
  7. HashMap<String,String> map = new HashMap<>();
  8. map.put("张三","110");
  9. map.put("李四","119");
  10. map.put("王二","120");
  11. // 键重复,更新原有的
  12. map.put("王二","139");
  13. for (Map.Entry<String, String> entry : map.entrySet()) {
  14. System.out.println(entry.getKey()+" ---> "+entry.getValue());
  15. }
  16. }
  17. }
  18. // 打印
  19. 李四 ---> 119
  20. 张三 ---> 110
  21. 王二 ---> 139

源码分析

基于JDK1.8。

不重要的方法已经清除,保留的方法已经注释。

ArrayList

  1. package java.util;
  2. import java.util.function.Consumer;
  3. import java.util.function.Predicate;
  4. import java.util.function.UnaryOperator;
  5. import sun.misc.SharedSecrets;
  6. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  7. {
  8. /** * 默认容量 */
  9. private static final int DEFAULT_CAPACITY = 10;
  10. /** * 空数组,用作初始化 */
  11. private static final Object[] EMPTY_ELEMENTDATA = { };
  12. /** * 共享空数组 */
  13. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = { };
  14. /** * 存放数据数 */
  15. transient Object[] elementData; // non-private to simplify nested class access
  16. /** * 数组大小,elementData存储元素数量同步 */
  17. private int size;
  18. /** * 构造器 */
  19. public ArrayList(int initialCapacity) {
  20. if (initialCapacity > 0) {
  21. this.elementData = new Object[initialCapacity];
  22. } else if (initialCapacity == 0) {
  23. this.elementData = EMPTY_ELEMENTDATA;
  24. } else { // inittialCapatity < 0 抛出异常
  25. throw new IllegalArgumentException("Illegal Capacity: "+
  26. initialCapacity);
  27. }
  28. }
  29. /** * 构造器 */
  30. public ArrayList() {
  31. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  32. }
  33. /** * 构造器 */
  34. public ArrayList(Collection<? extends E> c) {
  35. elementData = c.toArray(); // c!= null
  36. if ((size = elementData.length) != 0) {
  37. if (elementData.getClass() != Object[].class)
  38. // 不是一个一个取值赋值给elementData,copyOf使用System.arrayCopy(), arrayCopy使用本地方法(JNI)效率很高
  39. elementData = Arrays.copyOf(elementData, size, Object[].class);
  40. } else {
  41. // replace with empty array.
  42. this.elementData = EMPTY_ELEMENTDATA;
  43. }
  44. }
  45. /** * 去掉数组(elementData)中不存数据的部分 */
  46. public void trimToSize() {
  47. modCount++;
  48. if (size < elementData.length) {
  49. elementData = (size == 0)
  50. ? EMPTY_ELEMENTDATA
  51. : Arrays.copyOf(elementData, size);
  52. }
  53. }
  54. /** * 调整List大小,可以扩容和缩容,缩容时最小容量不小于10 */
  55. public void ensureCapacity(int minCapacity) {
  56. int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
  57. ? 0
  58. : DEFAULT_CAPACITY;
  59. // 小于最小容量不调整,因此最小容量不会小于10
  60. if (minCapacity > minExpand) {
  61. ensureExplicitCapacity(minCapacity);
  62. }
  63. }
  64. /** * 最大容量 */
  65. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  66. /** * 动态扩容方法, 容量为之前的1.5倍 oldCapacity + (oldCapacity >> 1) */
  67. private void grow(int minCapacity) {
  68. // overflow-conscious code
  69. int oldCapacity = elementData.length;
  70. int newCapacity = oldCapacity + (oldCapacity >> 1);
  71. if (newCapacity - minCapacity < 0)
  72. newCapacity = minCapacity;
  73. if (newCapacity - MAX_ARRAY_SIZE > 0)
  74. newCapacity = hugeCapacity(minCapacity);
  75. // minCapacity is usually close to size, so this is a win:
  76. elementData = Arrays.copyOf(elementData, newCapacity);
  77. }
  78. private static int hugeCapacity(int minCapacity) {
  79. if (minCapacity < 0) // overflow
  80. throw new OutOfMemoryError();
  81. return (minCapacity > MAX_ARRAY_SIZE) ?
  82. Integer.MAX_VALUE :
  83. MAX_ARRAY_SIZE;
  84. }
  85. /** * 获取list大小 */
  86. public int size() {
  87. return size;
  88. }
  89. /** * 判断list是否为空 */
  90. public boolean isEmpty() {
  91. return size == 0;
  92. }
  93. // 每次取出元素操作时都会调用此方法对Ojbect数组原型进行类型转换
  94. E elementData(int index) {
  95. return (E) elementData[index];
  96. }
  97. /** * 获取元素 */
  98. public E get(int index) {
  99. rangeCheck(index); // 检查是否越界
  100. return elementData(index);
  101. }
  102. /** * 添加元素 */
  103. public boolean add(E e) {
  104. ensureCapacityInternal(size + 1); // Increments modCount!!
  105. elementData[size++] = e;
  106. return true;
  107. }
  108. /** * 删除 */
  109. public E remove(int index) {
  110. rangeCheck(index);
  111. modCount++;
  112. E oldValue = elementData(index);
  113. int numMoved = size - index - 1;
  114. if (numMoved > 0)
  115. System.arraycopy(elementData, index+1, elementData, index,
  116. numMoved);
  117. elementData[--size] = null;
  118. return oldValue;
  119. }
  120. /** * 两个list做差集 */
  121. public boolean retainAll(Collection<?> c) {
  122. Objects.requireNonNull(c);
  123. return batchRemove(c, true);
  124. }
  125. /** * 批量移除 */
  126. private boolean batchRemove(Collection<?> c, boolean complement) {
  127. final Object[] elementData = this.elementData;
  128. int r = 0, w = 0;
  129. boolean modified = false;
  130. try {
  131. for (; r < size; r++)
  132. if (c.contains(elementData[r]) == complement)
  133. elementData[w++] = elementData[r];
  134. } finally {
  135. if (r != size) {
  136. System.arraycopy(elementData, r,
  137. elementData, w,
  138. size - r);
  139. w += size - r;
  140. }
  141. if (w != size) {
  142. // clear to let GC do its work
  143. for (int i = w; i < size; i++)
  144. elementData[i] = null;
  145. modCount += size - w;
  146. size = w;
  147. modified = true;
  148. }
  149. }
  150. return modified;
  151. }
  152. @Override
  153. public void forEach(Consumer<? super E> action) {
  154. Objects.requireNonNull(action);
  155. final int expectedModCount = modCount;
  156. @SuppressWarnings("unchecked")
  157. final E[] elementData = (E[]) this.elementData;
  158. final int size = this.size;
  159. for (int i=0; modCount == expectedModCount && i < size; i++) {
  160. // 调用回调 (e)->{ //操作e }
  161. action.accept(elementData[i]);
  162. }
  163. // 遍历过程禁止修改list!
  164. if (modCount != expectedModCount) {
  165. throw new ConcurrentModificationException();
  166. }
  167. }
  168. /** * 移除步骤: * 1. 标记移除 * 2. 修改线程 * 3. 移动元素 * 4. 清除尾部元素 */
  169. @Override
  170. public boolean removeIf(Predicate<? super E> filter) {
  171. Objects.requireNonNull(filter);
  172. int removeCount = 0;
  173. final BitSet removeSet = new BitSet(size);
  174. final int expectedModCount = modCount;
  175. final int size = this.size;
  176. // 标记元素
  177. for (int i=0; modCount == expectedModCount && i < size; i++) {
  178. @SuppressWarnings("unchecked")
  179. final E element = (E) elementData[i];
  180. if (filter.test(element)) {
  181. removeSet.set(i);
  182. removeCount++;
  183. }
  184. }
  185. if (modCount != expectedModCount) {
  186. throw new ConcurrentModificationException();
  187. }
  188. // shift surviving elements left over the spaces left by removed elements
  189. final boolean anyToRemove = removeCount > 0;
  190. if (anyToRemove) {
  191. final int newSize = size - removeCount;
  192. // 移动元素 例如: [1][2][3] size=2 移动后 [1][3][3]
  193. for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
  194. i = removeSet.nextClearBit(i);
  195. elementData[j] = elementData[i];
  196. }
  197. // 清除尾部元素
  198. for (int k=newSize; k < size; k++) {
  199. elementData[k] = null; // Let gc do its work
  200. }
  201. // 更新size
  202. this.size = newSize;
  203. if (modCount != expectedModCount) {
  204. throw new ConcurrentModificationException();
  205. }
  206. modCount++;
  207. }
  208. return anyToRemove;
  209. }
  210. }

HashMap

底层数据结构:数组链表+红黑树

默认的容量为:16(1<<4)

扩容的条件:size>=容量*加载因子

扩容大小:旧容量2倍(newCap = oldCap << 1)

树化(terrify)的条件

  1. 容量长度大于等于64
  2. 链表成都大于8

树化的过程

  1. 把普通节点转换为TreeNode
  2. 调用treeify进行树化

    1. 调整节点
    2. 左旋右旋

put导致死循环的原因。在JDK1.7中插入元素使用头插法,插入的时候不需要遍历哈希桶,在多线程下这样可能形成循环链表。JDK8采用尾插法,循环找到最后一个节点,然后在最后一个节点插入元素。

存储结构

image.png

  1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
  2. /** * 默认容量16 */
  3. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  4. /** * 最大容量,1 << 30 = 1073741824 */
  5. static final int MAXIMUM_CAPACITY = 1 << 30;
  6. /** * 默认加载因子,是决定存储容量扩容的关键指标,计算公式: size/总容量 */
  7. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  8. /** * 小于这个值无法使用红黑树,HashMap容量不推荐为奇数,比这个数小后树退化为数组 * 红黑树扩展时也参考这个属性 */
  9. static final int TREEIFY_THRESHOLD = 8;
  10. /** * 容量小于这个值红黑树将退化为数组存储 */
  11. static final int UNTREEIFY_THRESHOLD = 6;
  12. /** * 将数组转化为红黑树推荐的容量 */
  13. static final int MIN_TREEIFY_CAPACITY = 64;
  14. /** * 使用数组存储的数据结构,node节点 */
  15. static class Node<K,V> implements Map.Entry<K,V> {
  16. final int hash;
  17. final K key;
  18. V value;
  19. Node<K,V> next;
  20. Node(int hash, K key, V value, Node<K,V> next) {
  21. this.hash = hash;
  22. this.key = key;
  23. this.value = value;
  24. this.next = next;
  25. }
  26. }
  27. /** * 计算对象的hash值,是hash code分配更均匀,减少冲突几率 */
  28. static final int hash(Object key) {
  29. int h;
  30. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  31. }
  32. /** * 计算2的幂次方表容量 * 也就是说表容量只能为: ... 4 8 16 32 64 128 256 ... 1024 ... 1073741824 */
  33. static final int tableSizeFor(int cap) {
  34. int n = cap - 1;
  35. n |= n >>> 1;
  36. n |= n >>> 2;
  37. n |= n >>> 4;
  38. n |= n >>> 8;
  39. n |= n >>> 16;
  40. return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  41. }
  42. /* ---------------- Fields -------------- */
  43. /** * 数组存储结构,默认第一次使用时会分配空间 */
  44. transient Node<K,V>[] table;
  45. /** * 键值对数量 */
  46. transient int size;
  47. /** * 对table修改的次数,调整table时改变 —— rehash、remove、add等操作 * 用来判断在读取操作过程中是否出现table修改 */
  48. transient int modCount;
  49. /** * 扩容时的临界值,计算为 capacity*loadFactor */
  50. int threshold;
  51. /** * 加载因子, 默认0.75 */
  52. final float loadFactor;
  53. /* ---------------- Public operations -------------- */
  54. /** * 默认构造函数,table容量为16 */
  55. public HashMap() {
  56. this.loadFactor = DEFAULT_LOAD_FACTOR; // 0.75
  57. }
  58. /** * 获取存储键值对数量 */
  59. public int size() {
  60. return size;
  61. }
  62. /** * 判空 */
  63. public boolean isEmpty() {
  64. return size == 0;
  65. }
  66. /** * 通过key获取value * 下面的getNode是核心方法。 */
  67. public V get(Object key) {
  68. Node<K,V> e;
  69. return (e = getNode(hash(key), key)) == null ? null : e.value;
  70. }
  71. /** * 获取操作 */
  72. final Node<K,V> getNode(int hash, Object key) {
  73. Node<K,V>[] tab;
  74. Node<K,V> first, e;
  75. int n; // n table长度
  76. K k;
  77. if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
  78. if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
  79. return first;
  80. if ((e = first.next) != null) {
  81. // 根据存储结构来获取数据
  82. // 红黑树,调用getTreeNode
  83. if (first instanceof TreeNode)
  84. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  85. // 遍历链表
  86. do {
  87. //较key查询value
  88. if (e.hash == hash &&
  89. ((k = e.key) == key || (key != null && key.equals(k))))
  90. return e;
  91. } while ((e = e.next) != null);
  92. }
  93. }
  94. return null;
  95. }
  96. /** * 添加数据 */
  97. public V put(K key, V value) {
  98. return putVal(hash(key), key, value, false, true);
  99. }
  100. /** * Implements Map.put and related methods. * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. */
  101. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  102. boolean evict) {
  103. Node<K,V>[] tab; Node<K,V> p; int n, i;
  104. // table未初始化会执行
  105. if ((tab = table) == null || (n = tab.length) == 0)
  106. n = (tab = resize()).length;
  107. // 存放值
  108. if ((p = tab[i = (n - 1) & hash]) == null)// 判断通过hash计算出的位置是否有值
  109. // 没有就在该位置(i)创建一个node并赋值
  110. tab[i] = newNode(hash, key, value, null);
  111. else { // 这里时计算出的位置有值存在
  112. Node<K,V> e; K k;
  113. if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
  114. // 判断hash值、key相同,认为
  115. e = p;
  116. else if (p instanceof TreeNode)
  117. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  118. else {
  119. // 遍历哈希桶
  120. for (int binCount = 0; ; ++binCount) {
  121. // 遍历到桶最后一个元素(链表最后一个元素)
  122. if ((e = p.next) == null) {
  123. // 添加元素
  124. p.next = newNode(hash, key, value, null);
  125. // 判断,只有哈希桶至少为8个的时候才进行树化,TREEIFY_THRESHOLD默认为8
  126. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  127. treeifyBin(tab, hash);
  128. break;
  129. }
  130. // 判断键值是否相同
  131. if (e.hash == hash &&
  132. ((k = e.key) == key || (key != null && key.equals(k))))
  133. break;
  134. // 下一个元素
  135. p = e;
  136. }
  137. }
  138. // 更新值
  139. if (e != null) { // existing mapping for key —— 存在键的映射
  140. V oldValue = e.value;
  141. if (!onlyIfAbsent || oldValue == null)
  142. e.value = value;
  143. afterNodeAccess(e);
  144. return oldValue;
  145. }
  146. }
  147. ++modCount;
  148. // 超出HashMap存放元素的阈值threshold = capacity * loadFactor(0.75)
  149. if (++size > threshold)
  150. // 调整Hash存在空间大小
  151. resize();
  152. afterNodeInsertion(evict);
  153. return null;
  154. }
  155. /** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */
  156. final Node<K,V>[] resize() {
  157. Node<K,V>[] oldTab = table;
  158. // 旧容量,为哈希桶长度
  159. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  160. int oldThr = threshold;
  161. int newCap, newThr = 0;
  162. // 这个if用来保证HashMap阈值threshold不超限
  163. if (oldCap > 0) {
  164. // 判断是否超出最大容量,到最大容量不再扩容
  165. if (oldCap >= MAXIMUM_CAPACITY) {
  166. // 阈值设置整型最大值
  167. threshold = Integer.MAX_VALUE;
  168. // 返回并不再调整大小
  169. return oldTab;
  170. }
  171. // 在容量范围内
  172. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
  173. newThr = oldThr << 1; // double threshold 为原先的两倍
  174. }
  175. else if (oldThr > 0) // initial capacity was placed in threshold
  176. newCap = oldThr;
  177. else { // zero initial threshold signifies using defaults
  178. newCap = DEFAULT_INITIAL_CAPACITY;
  179. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  180. }
  181. // 计算加载因子,设置新的阈值 阈值=新容量*加载因子
  182. if (newThr == 0) {
  183. float ft = (float)newCap * loadFactor;
  184. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  185. (int)ft : Integer.MAX_VALUE);
  186. }
  187. threshold = newThr;
  188. // 新的哈希桶
  189. @SuppressWarnings({ "rawtypes","unchecked"})
  190. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  191. table = newTab;
  192. // 将旧桶的元素更新到新桶
  193. if (oldTab != null) {
  194. for (int j = 0; j < oldCap; ++j) {
  195. Node<K,V> e;
  196. if ((e = oldTab[j]) != null) {
  197. oldTab[j] = null;
  198. if (e.next == null)
  199. // 旧桶中的值移动到新桶
  200. newTab[e.hash & (newCap - 1)] = e;
  201. else if (e instanceof TreeNode)
  202. // 执行红黑树操作
  203. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  204. else { // preserve order - 翻转顺序
  205. Node<K,V> loHead = null, loTail = null;
  206. Node<K,V> hiHead = null, hiTail = null;
  207. Node<K,V> next;
  208. do {
  209. next = e.next;
  210. if ((e.hash & oldCap) == 0) {
  211. if (loTail == null)
  212. loHead = e;
  213. else
  214. loTail.next = e;
  215. loTail = e;
  216. }
  217. else {
  218. if (hiTail == null)
  219. hiHead = e;
  220. else
  221. hiTail.next = e;
  222. hiTail = e;
  223. }
  224. } while ((e = next) != null);
  225. if (loTail != null) {
  226. loTail.next = null;
  227. newTab[j] = loHead;
  228. }
  229. if (hiTail != null) {
  230. hiTail.next = null;
  231. newTab[j + oldCap] = hiHead;
  232. }
  233. }
  234. }
  235. }
  236. }
  237. return newTab;
  238. }
  239. /** * 树化方法 * Replaces all linked nodes in bin at index for given hash unless * table is too small, in which case resizes instead. */
  240. final void treeifyBin(Node<K,V>[] tab, int hash) {
  241. int n, index; Node<K,V> e;
  242. if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
  243. resize();
  244. else if ((e = tab[index = (n - 1) & hash]) != null) {
  245. TreeNode<K,V> hd = null, tl = null;
  246. do {
  247. TreeNode<K,V> p = replacementTreeNode(e, null);
  248. if (tl == null)
  249. hd = p;
  250. else {
  251. p.prev = tl;
  252. tl.next = p;
  253. }
  254. tl = p;
  255. } while ((e = e.next) != null);
  256. if ((tab[index] = hd) != null)
  257. hd.treeify(tab);
  258. }
  259. }
  260. /* ------------------------------------------------------------ */
  261. // Tree bins
  262. /** * 红黑树 * * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */
  263. static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
  264. TreeNode<K,V> parent; // red-black tree links
  265. TreeNode<K,V> left;
  266. TreeNode<K,V> right;
  267. TreeNode<K,V> prev; // needed to unlink next upon deletion
  268. boolean red;
  269. TreeNode(int hash, K key, V val, Node<K,V> next) {
  270. super(hash, key, val, next);
  271. }
  272. }
  273. }

(完)


文章同步我的个人博客:https://www.elltor.com/archives/106.html

发表评论

表情:
评论列表 (有 0 条评论,553人围观)

还没有评论,来说两句吧...

相关阅读

    相关 深入理解Java集合框架性能问题

    Java集合框架是Java编程中用于存储和操作数据的工具包。在使用过程中,可能会遇到一些性能问题,以下是一些常见的理解和解决策略: 1. **数据量过大**:如果一个集合包含