Java集合概述

集合类结构与关系

Map结尾的实现了Map接口,其他的都实现了Collection接口.
image.png

Map接口源码

JDK版本1.8.0_261,可以看到除了一些容器的增,删,查,迭代操作以外,还有一些JDK1.8以后提供的默认方法和静态方法,使用到了函数式编程参数传入的是一个Funcation对象。

  1. package java.util;
  2. import java.util.function.BiConsumer;
  3. import java.util.function.BiFunction;
  4. import java.util.function.Function;
  5. import java.io.Serializable;
  6. *
  7. * @param <K> the type of keys maintained by this map
  8. * @param <V> the type of mapped values
  9. *
  10. * @author Josh Bloch
  11. * @see HashMap
  12. * @see TreeMap
  13. * @see Hashtable
  14. * @see SortedMap
  15. * @see Collection
  16. * @see Set
  17. * @since 1.2
  18. */
  19. public interface Map<K,V> {
  20. int size();
  21. boolean isEmpty();
  22. boolean containsKey(Object key);
  23. boolean containsValue(Object value);
  24. V get(Object key);
  25. V put(K key, V value);
  26. V remove(Object key);
  27. void putAll(Map<? extends K, ? extends V> m);
  28. void clear();
  29. Set<K> keySet();
  30. Collection<V> values();
  31. Set<Map.Entry<K, V>> entrySet();
  32. interface Entry<K,V> {
  33. K getKey();
  34. V getValue();
  35. V setValue(V value);
  36. boolean equals(Object o);
  37. int hashCode();
  38. /**
  39. * @since 1.8
  40. */
  41. public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
  42. return (Comparator<Map.Entry<K, V>> & Serializable)
  43. (c1, c2) -> c1.getKey().compareTo(c2.getKey());
  44. }
  45. /**
  46. * @since 1.8
  47. */
  48. public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
  49. return (Comparator<Map.Entry<K, V>> & Serializable)
  50. (c1, c2) -> c1.getValue().compareTo(c2.getValue());
  51. }
  52. /**
  53. * @since 1.8
  54. */
  55. public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
  56. Objects.requireNonNull(cmp);
  57. return (Comparator<Map.Entry<K, V>> & Serializable)
  58. (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
  59. }
  60. /**
  61. * @since 1.8
  62. */
  63. public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
  64. Objects.requireNonNull(cmp);
  65. return (Comparator<Map.Entry<K, V>> & Serializable)
  66. (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
  67. }
  68. }
  69. boolean equals(Object o);
  70. int hashCode();
  71. // Defaultable methods
  72. /**
  73. * @since 1.8
  74. */
  75. default V getOrDefault(Object key, V defaultValue) {
  76. V v;
  77. return (((v = get(key)) != null) || containsKey(key))
  78. ? v
  79. : defaultValue;
  80. }
  81. /**
  82. * @since 1.8
  83. */
  84. default void forEach(BiConsumer<? super K, ? super V> action) {
  85. Objects.requireNonNull(action);
  86. for (Map.Entry<K, V> entry : entrySet()) {
  87. K k;
  88. V v;
  89. try {
  90. k = entry.getKey();
  91. v = entry.getValue();
  92. } catch(IllegalStateException ise) {
  93. // this usually means the entry is no longer in the map.
  94. throw new ConcurrentModificationException(ise);
  95. }
  96. action.accept(k, v);
  97. }
  98. }
  99. /**
  100. * @since 1.8
  101. */
  102. default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
  103. Objects.requireNonNull(function);
  104. for (Map.Entry<K, V> entry : entrySet()) {
  105. K k;
  106. V v;
  107. try {
  108. k = entry.getKey();
  109. v = entry.getValue();
  110. } catch(IllegalStateException ise) {
  111. // this usually means the entry is no longer in the map.
  112. throw new ConcurrentModificationException(ise);
  113. }
  114. // ise thrown from function is not a cme.
  115. v = function.apply(k, v);
  116. try {
  117. entry.setValue(v);
  118. } catch(IllegalStateException ise) {
  119. // this usually means the entry is no longer in the map.
  120. throw new ConcurrentModificationException(ise);
  121. }
  122. }
  123. }
  124. /**
  125. * If the specified key is not already associated with a value (or is mapped
  126. * to {@code null}) associates it with the given value and returns
  127. * {@code null}, else returns the current value.
  128. *
  129. * @since 1.8
  130. */
  131. default V putIfAbsent(K key, V value) {
  132. V v = get(key);
  133. if (v == null) {
  134. v = put(key, value);
  135. }
  136. return v;
  137. }
  138. /**
  139. * Removes the entry for the specified key only if it is currently
  140. * mapped to the specified value.
  141. * @since 1.8
  142. */
  143. default boolean remove(Object key, Object value) {
  144. Object curValue = get(key);
  145. if (!Objects.equals(curValue, value) ||
  146. (curValue == null && !containsKey(key))) {
  147. return false;
  148. }
  149. remove(key);
  150. return true;
  151. }
  152. /**
  153. * Replaces the entry for the specified key only if currently
  154. * mapped to the specified value.
  155. *
  156. * @since 1.8
  157. */
  158. default boolean replace(K key, V oldValue, V newValue) {
  159. Object curValue = get(key);
  160. if (!Objects.equals(curValue, oldValue) ||
  161. (curValue == null && !containsKey(key))) {
  162. return false;
  163. }
  164. put(key, newValue);
  165. return true;
  166. }
  167. /**
  168. * Replaces the entry for the specified key only if it is
  169. * currently mapped to some value.
  170. *
  171. * @since 1.8
  172. */
  173. default V replace(K key, V value) {
  174. V curValue;
  175. if (((curValue = get(key)) != null) || containsKey(key)) {
  176. curValue = put(key, value);
  177. }
  178. return curValue;
  179. }
  180. /**
  181. * If the specified key is not already associated with a value (or is mapped
  182. * to {@code null}), attempts to compute its value using the given mapping
  183. * function and enters it into this map unless {@code null}.
  184. * @since 1.8
  185. */
  186. default V computeIfAbsent(K key,
  187. Function<? super K, ? extends V> mappingFunction) {
  188. Objects.requireNonNull(mappingFunction);
  189. V v;
  190. if ((v = get(key)) == null) {
  191. V newValue;
  192. if ((newValue = mappingFunction.apply(key)) != null) {
  193. put(key, newValue);
  194. return newValue;
  195. }
  196. }
  197. return v;
  198. }
  199. /**
  200. * If the value for the specified key is present and non-null, attempts to
  201. * compute a new mapping given the key and its current mapped value.
  202. *
  203. * <p>If the function returns {@code null}, the mapping is removed. If the
  204. * function itself throws an (unchecked) exception, the exception is
  205. * rethrown, and the current mapping is left unchanged.
  206. * @since 1.8
  207. */
  208. default V computeIfPresent(K key,
  209. BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  210. Objects.requireNonNull(remappingFunction);
  211. V oldValue;
  212. if ((oldValue = get(key)) != null) {
  213. V newValue = remappingFunction.apply(key, oldValue);
  214. if (newValue != null) {
  215. put(key, newValue);
  216. return newValue;
  217. } else {
  218. remove(key);
  219. return null;
  220. }
  221. } else {
  222. return null;
  223. }
  224. }
  225. /**
  226. * Attempts to compute a mapping for the specified key and its current
  227. * mapped value (or {@code null} if there is no current mapping). For
  228. * example, to either create or append a {@code String} msg to a value
  229. * mapping:
  230. *
  231. * @since 1.8
  232. */
  233. default V compute(K key,
  234. BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  235. Objects.requireNonNull(remappingFunction);
  236. V oldValue = get(key);
  237. V newValue = remappingFunction.apply(key, oldValue);
  238. if (newValue == null) {
  239. // delete mapping
  240. if (oldValue != null || containsKey(key)) {
  241. // something to remove
  242. remove(key);
  243. return null;
  244. } else {
  245. // nothing to do. Leave things as they were.
  246. return null;
  247. }
  248. } else {
  249. // add or replace old mapping
  250. put(key, newValue);
  251. return newValue;
  252. }
  253. }
  254. /**
  255. * If the specified key is not already associated with a value or is
  256. * associated with null, associates it with the given non-null value.
  257. * Otherwise, replaces the associated value with the results of the given
  258. * remapping function, or removes if the result is {@code null}. This
  259. * method may be of use when combining multiple mapped values for a key.
  260. * For example, to either create or append a {@code String msg} to a
  261. * value mapping:
  262. * @since 1.8
  263. */
  264. default V merge(K key, V value,
  265. BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
  266. Objects.requireNonNull(remappingFunction);
  267. Objects.requireNonNull(value);
  268. V oldValue = get(key);
  269. V newValue = (oldValue == null) ? value :
  270. remappingFunction.apply(oldValue, value);
  271. if(newValue == null) {
  272. remove(key);
  273. } else {
  274. put(key, newValue);
  275. }
  276. return newValue;
  277. }
  278. }

Iterable源码

主要的方法只有一个iterator,但是为了支持Java8的函数式编程Stream也提供了一个默认方法for Each

  1. package java.lang;
  2. import java.util.Iterator;
  3. import java.util.Objects;
  4. import java.util.Spliterator;
  5. import java.util.Spliterators;
  6. import java.util.function.Consumer;
  7. /**
  8. * Implementing this interface allows an object to be the target of
  9. * the "for-each loop" statement.
  10. *
  11. * @since 1.5
  12. * @jls 14.14.2 The enhanced for statement
  13. */
  14. public interface Iterable<T> {
  15. /**
  16. * Returns an iterator over elements of type {@code T}.
  17. *
  18. * @return an Iterator.
  19. */
  20. Iterator<T> iterator();
  21. /**
  22. * Performs the given action for each element of the {@code Iterable}
  23. * until all elements have been processed or the action throws an
  24. * exception. Unless otherwise specified by the implementing class,
  25. * actions are performed in the order of iteration (if an iteration order
  26. * is specified). Exceptions thrown by the action are relayed to the
  27. * caller
  28. * @since 1.8
  29. */
  30. default void forEach(Consumer<? super T> action) {
  31. Objects.requireNonNull(action);
  32. for (T t : this) {
  33. action.accept(t);
  34. }
  35. }
  36. /**
  37. * Creates a {@link Spliterator} over the elements described by this
  38. * {@code Iterable}.
  39. * @since 1.8
  40. */
  41. default Spliterator<T> spliterator() {
  42. return Spliterators.spliteratorUnknownSize(iterator(), 0);
  43. }
  44. }

Collection源码

同样,为了支持Stream操作,增加了一些默认方法

  1. package java.util;
  2. import java.util.function.Predicate;
  3. import java.util.stream.Stream;
  4. import java.util.stream.StreamSupport;
  5. /**
  6. * The root interface in the <i>collection hierarchy</i>. A collection
  7. * represents a group of objects, known as its <i>elements</i>. Some
  8. * collections allow duplicate elements and others do not. Some are ordered
  9. * and others unordered. The JDK does not provide any <i>direct</i>
  10. * implementations of this interface: it provides implementations of more
  11. * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface
  12. * is typically used to pass collections around and manipulate them where
  13. * maximum generality is desired.
  14. *
  15. * @author Josh Bloch
  16. * @author Neal Gafter
  17. * @see Set
  18. * @see List
  19. * @see Map
  20. * @see SortedSet
  21. * @see SortedMap
  22. * @see HashSet
  23. * @see TreeSet
  24. * @see ArrayList
  25. * @see LinkedList
  26. * @see Vector
  27. * @see Collections
  28. * @see Arrays
  29. * @see AbstractCollection
  30. * @since 1.2
  31. */
  32. public interface Collection<E> extends Iterable<E> {
  33. int size();
  34. boolean isEmpty();
  35. boolean contains(Object o);
  36. Iterator<E> iterator();
  37. Object[] toArray();
  38. <T> T[] toArray(T[] a);
  39. boolean add(E e);
  40. boolean remove(Object o);
  41. boolean containsAll(Collection<?> c);
  42. boolean addAll(Collection<? extends E> c);
  43. boolean removeAll(Collection<?> c);
  44. /**
  45. * Removes all of the elements of this collection that satisfy the given
  46. * predicate. Errors or runtime exceptions thrown during iteration or by
  47. * the predicate are relayed to the caller.
  48. * @since 1.8
  49. */
  50. default boolean removeIf(Predicate<? super E> filter) {
  51. Objects.requireNonNull(filter);
  52. boolean removed = false;
  53. final Iterator<E> each = iterator();
  54. while (each.hasNext()) {
  55. if (filter.test(each.next())) {
  56. each.remove();
  57. removed = true;
  58. }
  59. }
  60. return removed;
  61. }
  62. boolean retainAll(Collection<?> c);
  63. void clear();
  64. boolean equals(Object o);
  65. int hashCode();
  66. /**
  67. * Creates a {@link Spliterator} over the elements in this collection.
  68. * @since 1.8
  69. */
  70. @Override
  71. default Spliterator<E> spliterator() {
  72. return Spliterators.spliterator(this, 0);
  73. }
  74. /**
  75. * Returns a sequential {@code Stream} with this collection as its source.
  76. * @since 1.8
  77. */
  78. default Stream<E> stream() {
  79. return StreamSupport.stream(spliterator(), false);
  80. }
  81. /**
  82. * Returns a possibly parallel {@code Stream} with this collection as its
  83. * source. It is allowable for this method to return a sequential stream.
  84. * @since 1.8
  85. */
  86. default Stream<E> parallelStream() {
  87. return StreamSupport.stream(spliterator(), true);
  88. }
  89. }

HashMap源码解析

简介

HashMap采用key/value存储结构,每个key对应唯一的value,查询和修改的速度都很快,能达到O(1)的平均时间复杂度。它是非线程安全的,且不保证元素存储的顺序;

继承体系

Java基础-容器 - 图2
HashMap实现了Cloneable,可以被克隆。
HashMap实现了Serializable,可以被序列化。

HashMap继承自AbstractMap,实现了Map接口,具有Map的所有功能。

存储结构

Java基础-容器 - 图3
在Java中,HashMap的实现采用了(数组 + 链表 + 红黑树)的复杂结构,数组的一个元素又称作桶。
在添加元素时,会根据hash值算出元素在数组中的位置,如果该位置没有元素,则直接把元素放置在此处,如果该位置有元素了,则把元素以链表的形式放置在链表的尾部。
当一个链表的元素个数达到一定的数量(且数组的长度达到一定的长度)后,则把链表转化为红黑树,从而提高效率。
数组的查询效率为O(1),链表的查询效率是O(k),红黑树的查询效率是O(log k),k为桶中的元素个数,所以当元素数量非常多的时候,转化为红黑树能极大地提高效率。

源码解析

属性

  1. /**
  2. * 默认的初始容量为16
  3. */
  4. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
  5. /**
  6. * 最大的容量为2的30次方
  7. */
  8. static final int MAXIMUM_CAPACITY = 1 << 30;
  9. /**
  10. * 默认的装载因子
  11. */
  12. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  13. /**
  14. * 当一个桶中的元素个数大于等于8时进行树化
  15. */
  16. static final int TREEIFY_THRESHOLD = 8;
  17. /**
  18. * 当一个桶中的元素个数小于等于6时把树转化为链表
  19. */
  20. static final int UNTREEIFY_THRESHOLD = 6;
  21. /**
  22. * 当桶的个数达到64的时候才进行树化
  23. */
  24. static final int MIN_TREEIFY_CAPACITY = 64;
  25. /**
  26. * 数组,又叫作桶(bucket)
  27. */
  28. transient Node<K,V>[] table;
  29. /**
  30. * 作为entrySet()的缓存
  31. */
  32. transient Set<Map.Entry<K,V>> entrySet;
  33. /**
  34. * 元素的数量
  35. */
  36. transient int size;
  37. /**
  38. * 修改次数,用于在迭代的时候执行快速失败策略
  39. */
  40. transient int modCount;
  41. /**
  42. * 当桶的使用数量达到多少时进行扩容,threshold = capacity * loadFactor
  43. */
  44. int threshold;
  45. /**
  46. * 装载因子
  47. */
  48. final float loadFactor;
  49. 复制代码

(1)容量
容量为数组的长度,亦即桶的个数,默认为16,最大为2的30次方,当容量达到64时才可以树化。
(2)装载因子
装载因子用来计算容量达到多少时才进行扩容,默认装载因子为0.75。
(3)树化
树化,当容量达到64且链表的长度达到8时进行树化,当链表的长度小于6时反树化。

Node内部类-链表基类

Node是一个典型的单链表节点,其中,hash用来存储key计算得来的hash值。

  1. /**
  2. * Basic hash bin node, used for most entries. (See below for
  3. * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
  4. */
  5. static class Node<K,V> implements Map.Entry<K,V> {
  6. final int hash; //Key计算出来的Hash值
  7. final K key;
  8. V value;
  9. Node<K,V> next;
  10. Node(int hash, K key, V value, Node<K,V> next) {
  11. this.hash = hash;
  12. this.key = key;
  13. this.value = value;
  14. this.next = next;
  15. }
  16. public final K getKey() { return key; }
  17. public final V getValue() { return value; }
  18. public final String toString() { return key + "=" + value; }
  19. public final int hashCode() {
  20. return Objects.hashCode(key) ^ Objects.hashCode(value);
  21. }
  22. public final V setValue(V newValue) {
  23. V oldValue = value;
  24. value = newValue;
  25. return oldValue;
  26. }
  27. public final boolean equals(Object o) {
  28. if (o == this)
  29. return true;
  30. if (o instanceof Map.Entry) {
  31. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  32. if (Objects.equals(key, e.getKey()) &&
  33. Objects.equals(value, e.getValue()))
  34. return true;
  35. }
  36. return false;
  37. }
  38. }
  39. 复制代码

TreeNode内部类-红黑树基类

这是一个神奇的类,它继承自LinkedHashMap中的Entry类,关于LInkedHashMap.Entry这个类我们后面再讲。
TreeNode是一个典型的树型节点,它实现了一颗红黑树,其中,prev是链表中的节点,用于在删除元素的时候可以快速找到它的前置节点。

  1. /**
  2. * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
  3. * extends Node) so can be used as extension of either regular or
  4. * linked node.
  5. */
  6. static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
  7. TreeNode<K,V> parent; //red-black tree links
  8. TreeNode<K,V> left;
  9. TreeNode<K,V> right;
  10. TreeNode<K,V> prev; // needed to unlink next upon deletion
  11. boolean red;
  12. TreeNode(int hash, K key, V val, Node<K,V> next) {
  13. super(hash, key, val, next);
  14. }
  15. /**
  16. * Returns root of tree containing this node.
  17. */
  18. final TreeNode<K,V> root() {
  19. for (TreeNode<K,V> r = this, p;;) {
  20. if ((p = r.parent) == null)
  21. return r;
  22. r = p;
  23. }
  24. }
  25. /**
  26. * Ensures that the given root is the first node of its bin.
  27. */
  28. static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
  29. int n;
  30. if (root != null && tab != null && (n = tab.length) > 0) {
  31. int index = (n - 1) & root.hash;
  32. TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
  33. if (root != first) {
  34. Node<K,V> rn;
  35. tab[index] = root;
  36. TreeNode<K,V> rp = root.prev;
  37. if ((rn = root.next) != null)
  38. ((TreeNode<K,V>)rn).prev = rp;
  39. if (rp != null)
  40. rp.next = rn;
  41. if (first != null)
  42. first.prev = root;
  43. root.next = first;
  44. root.prev = null;
  45. }
  46. assert checkInvariants(root);
  47. }
  48. }
  49. /**
  50. * Finds the node starting at root p with the given hash and key.
  51. * The kc argument caches comparableClassFor(key) upon first use
  52. * comparing keys.
  53. */
  54. final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
  55. TreeNode<K,V> p = this;
  56. do {
  57. int ph, dir; K pk;
  58. TreeNode<K,V> pl = p.left, pr = p.right, q;
  59. if ((ph = p.hash) > h)
  60. p = pl;
  61. else if (ph < h)
  62. p = pr;
  63. else if ((pk = p.key) == k || (k != null && k.equals(pk)))
  64. return p;
  65. else if (pl == null)
  66. p = pr;
  67. else if (pr == null)
  68. p = pl;
  69. else if ((kc != null ||
  70. (kc = comparableClassFor(k)) != null) &&
  71. (dir = compareComparables(kc, k, pk)) != 0)
  72. p = (dir < 0) ? pl : pr;
  73. else if ((q = pr.find(h, k, kc)) != null)
  74. return q;
  75. else
  76. p = pl;
  77. } while (p != null);
  78. return null;
  79. }
  80. /**
  81. * Calls find for root node.
  82. */
  83. final TreeNode<K,V> getTreeNode(int h, Object k) {
  84. return ((parent != null) ? root() : this).find(h, k, null);
  85. }
  86. /**
  87. * Tie-breaking utility for ordering insertions when equal
  88. * hashCodes and non-comparable. We don't require a total
  89. * order, just a consistent insertion rule to maintain
  90. * equivalence across rebalancings. Tie-breaking further than
  91. * necessary simplifies testing a bit.
  92. */
  93. static int tieBreakOrder(Object a, Object b) {
  94. int d;
  95. if (a == null || b == null ||
  96. (d = a.getClass().getName().
  97. compareTo(b.getClass().getName())) == 0)
  98. d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
  99. -1 : 1);
  100. return d;
  101. }
  102. /**
  103. * Forms tree of the nodes linked from this node.
  104. */
  105. final void treeify(Node<K,V>[] tab) {
  106. TreeNode<K,V> root = null;
  107. for (TreeNode<K,V> x = this, next; x != null; x = next) {
  108. next = (TreeNode<K,V>)x.next;
  109. x.left = x.right = null;
  110. if (root == null) {
  111. x.parent = null;
  112. x.red = false;
  113. root = x;
  114. }
  115. else {
  116. K k = x.key;
  117. int h = x.hash;
  118. Class<?> kc = null;
  119. for (TreeNode<K,V> p = root;;) {
  120. int dir, ph;
  121. K pk = p.key;
  122. if ((ph = p.hash) > h)
  123. dir = -1;
  124. else if (ph < h)
  125. dir = 1;
  126. else if ((kc == null &&
  127. (kc = comparableClassFor(k)) == null) ||
  128. (dir = compareComparables(kc, k, pk)) == 0)
  129. dir = tieBreakOrder(k, pk);
  130. TreeNode<K,V> xp = p;
  131. if ((p = (dir <= 0) ? p.left : p.right) == null) {
  132. x.parent = xp;
  133. if (dir <= 0)
  134. xp.left = x;
  135. else
  136. xp.right = x;
  137. root = balanceInsertion(root, x);
  138. break;
  139. }
  140. }
  141. }
  142. }
  143. moveRootToFront(tab, root);
  144. }
  145. /**
  146. * Returns a list of non-TreeNodes replacing those linked from
  147. * this node.
  148. */
  149. final Node<K,V> untreeify(HashMap<K,V> map) {
  150. Node<K,V> hd = null, tl = null;
  151. for (Node<K,V> q = this; q != null; q = q.next) {
  152. Node<K,V> p = map.replacementNode(q, null);
  153. if (tl == null)
  154. hd = p;
  155. else
  156. tl.next = p;
  157. tl = p;
  158. }
  159. return hd;
  160. }
  161. /**
  162. * Tree version of putVal.
  163. */
  164. final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
  165. int h, K k, V v) {
  166. Class<?> kc = null;
  167. boolean searched = false;
  168. TreeNode<K,V> root = (parent != null) ? root() : this;
  169. for (TreeNode<K,V> p = root;;) {
  170. int dir, ph; K pk;
  171. if ((ph = p.hash) > h)
  172. dir = -1;
  173. else if (ph < h)
  174. dir = 1;
  175. else if ((pk = p.key) == k || (k != null && k.equals(pk)))
  176. return p;
  177. else if ((kc == null &&
  178. (kc = comparableClassFor(k)) == null) ||
  179. (dir = compareComparables(kc, k, pk)) == 0) {
  180. if (!searched) {
  181. TreeNode<K,V> q, ch;
  182. searched = true;
  183. if (((ch = p.left) != null &&
  184. (q = ch.find(h, k, kc)) != null) ||
  185. ((ch = p.right) != null &&
  186. (q = ch.find(h, k, kc)) != null))
  187. return q;
  188. }
  189. dir = tieBreakOrder(k, pk);
  190. }
  191. TreeNode<K,V> xp = p;
  192. if ((p = (dir <= 0) ? p.left : p.right) == null) {
  193. Node<K,V> xpn = xp.next;
  194. TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
  195. if (dir <= 0)
  196. xp.left = x;
  197. else
  198. xp.right = x;
  199. xp.next = x;
  200. x.parent = x.prev = xp;
  201. if (xpn != null)
  202. ((TreeNode<K,V>)xpn).prev = x;
  203. moveRootToFront(tab, balanceInsertion(root, x));
  204. return null;
  205. }
  206. }
  207. }
  208. /**
  209. * Removes the given node, that must be present before this call.
  210. * This is messier than typical red-black deletion code because we
  211. * cannot swap the contents of an interior node with a leaf
  212. * successor that is pinned by "next" pointers that are accessible
  213. * independently during traversal. So instead we swap the tree
  214. * linkages. If the current tree appears to have too few nodes,
  215. * the bin is converted back to a plain bin. (The test triggers
  216. * somewhere between 2 and 6 nodes, depending on tree structure).
  217. */
  218. final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
  219. boolean movable) {
  220. int n;
  221. if (tab == null || (n = tab.length) == 0)
  222. return;
  223. int index = (n - 1) & hash;
  224. TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
  225. TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
  226. if (pred == null)
  227. tab[index] = first = succ;
  228. else
  229. pred.next = succ;
  230. if (succ != null)
  231. succ.prev = pred;
  232. if (first == null)
  233. return;
  234. if (root.parent != null)
  235. root = root.root();
  236. if (root == null
  237. || (movable
  238. && (root.right == null
  239. || (rl = root.left) == null
  240. || rl.left == null))) {
  241. tab[index] = first.untreeify(map); // too small
  242. return;
  243. }
  244. TreeNode<K,V> p = this, pl = left, pr = right, replacement;
  245. if (pl != null && pr != null) {
  246. TreeNode<K,V> s = pr, sl;
  247. while ((sl = s.left) != null) // find successor
  248. s = sl;
  249. boolean c = s.red; s.red = p.red; p.red = c; // swap colors
  250. TreeNode<K,V> sr = s.right;
  251. TreeNode<K,V> pp = p.parent;
  252. if (s == pr) { // p was s's direct parent
  253. p.parent = s;
  254. s.right = p;
  255. }
  256. else {
  257. TreeNode<K,V> sp = s.parent;
  258. if ((p.parent = sp) != null) {
  259. if (s == sp.left)
  260. sp.left = p;
  261. else
  262. sp.right = p;
  263. }
  264. if ((s.right = pr) != null)
  265. pr.parent = s;
  266. }
  267. p.left = null;
  268. if ((p.right = sr) != null)
  269. sr.parent = p;
  270. if ((s.left = pl) != null)
  271. pl.parent = s;
  272. if ((s.parent = pp) == null)
  273. root = s;
  274. else if (p == pp.left)
  275. pp.left = s;
  276. else
  277. pp.right = s;
  278. if (sr != null)
  279. replacement = sr;
  280. else
  281. replacement = p;
  282. }
  283. else if (pl != null)
  284. replacement = pl;
  285. else if (pr != null)
  286. replacement = pr;
  287. else
  288. replacement = p;
  289. if (replacement != p) {
  290. TreeNode<K,V> pp = replacement.parent = p.parent;
  291. if (pp == null)
  292. root = replacement;
  293. else if (p == pp.left)
  294. pp.left = replacement;
  295. else
  296. pp.right = replacement;
  297. p.left = p.right = p.parent = null;
  298. }
  299. TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
  300. if (replacement == p) { // detach
  301. TreeNode<K,V> pp = p.parent;
  302. p.parent = null;
  303. if (pp != null) {
  304. if (p == pp.left)
  305. pp.left = null;
  306. else if (p == pp.right)
  307. pp.right = null;
  308. }
  309. }
  310. if (movable)
  311. moveRootToFront(tab, r);
  312. }
  313. /**
  314. * Splits nodes in a tree bin into lower and upper tree bins,
  315. * or untreeifies if now too small. Called only from resize;
  316. * see above discussion about split bits and indices.
  317. *
  318. * @param map the map
  319. * @param tab the table for recording bin heads
  320. * @param index the index of the table being split
  321. * @param bit the bit of hash to split on
  322. */
  323. final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
  324. TreeNode<K,V> b = this;
  325. // Relink into lo and hi lists, preserving order
  326. TreeNode<K,V> loHead = null, loTail = null;
  327. TreeNode<K,V> hiHead = null, hiTail = null;
  328. int lc = 0, hc = 0;
  329. for (TreeNode<K,V> e = b, next; e != null; e = next) {
  330. next = (TreeNode<K,V>)e.next;
  331. e.next = null;
  332. if ((e.hash & bit) == 0) {
  333. if ((e.prev = loTail) == null)
  334. loHead = e;
  335. else
  336. loTail.next = e;
  337. loTail = e;
  338. ++lc;
  339. }
  340. else {
  341. if ((e.prev = hiTail) == null)
  342. hiHead = e;
  343. else
  344. hiTail.next = e;
  345. hiTail = e;
  346. ++hc;
  347. }
  348. }
  349. if (loHead != null) {
  350. if (lc <= UNTREEIFY_THRESHOLD)
  351. tab[index] = loHead.untreeify(map);
  352. else {
  353. tab[index] = loHead;
  354. if (hiHead != null) // (else is already treeified)
  355. loHead.treeify(tab);
  356. }
  357. }
  358. if (hiHead != null) {
  359. if (hc <= UNTREEIFY_THRESHOLD)
  360. tab[index + bit] = hiHead.untreeify(map);
  361. else {
  362. tab[index + bit] = hiHead;
  363. if (loHead != null)
  364. hiHead.treeify(tab);
  365. }
  366. }
  367. }
  368. /* ------------------------------------------------------------ */
  369. // Red-black tree methods, all adapted from CLR
  370. static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
  371. TreeNode<K,V> p) {
  372. TreeNode<K,V> r, pp, rl;
  373. if (p != null && (r = p.right) != null) {
  374. if ((rl = p.right = r.left) != null)
  375. rl.parent = p;
  376. if ((pp = r.parent = p.parent) == null)
  377. (root = r).red = false;
  378. else if (pp.left == p)
  379. pp.left = r;
  380. else
  381. pp.right = r;
  382. r.left = p;
  383. p.parent = r;
  384. }
  385. return root;
  386. }
  387. static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
  388. TreeNode<K,V> p) {
  389. TreeNode<K,V> l, pp, lr;
  390. if (p != null && (l = p.left) != null) {
  391. if ((lr = p.left = l.right) != null)
  392. lr.parent = p;
  393. if ((pp = l.parent = p.parent) == null)
  394. (root = l).red = false;
  395. else if (pp.right == p)
  396. pp.right = l;
  397. else
  398. pp.left = l;
  399. l.right = p;
  400. p.parent = l;
  401. }
  402. return root;
  403. }
  404. static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
  405. TreeNode<K,V> x) {
  406. x.red = true;
  407. for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
  408. if ((xp = x.parent) == null) {
  409. x.red = false;
  410. return x;
  411. }
  412. else if (!xp.red || (xpp = xp.parent) == null)
  413. return root;
  414. if (xp == (xppl = xpp.left)) {
  415. if ((xppr = xpp.right) != null && xppr.red) {
  416. xppr.red = false;
  417. xp.red = false;
  418. xpp.red = true;
  419. x = xpp;
  420. }
  421. else {
  422. if (x == xp.right) {
  423. root = rotateLeft(root, x = xp);
  424. xpp = (xp = x.parent) == null ? null : xp.parent;
  425. }
  426. if (xp != null) {
  427. xp.red = false;
  428. if (xpp != null) {
  429. xpp.red = true;
  430. root = rotateRight(root, xpp);
  431. }
  432. }
  433. }
  434. }
  435. else {
  436. if (xppl != null && xppl.red) {
  437. xppl.red = false;
  438. xp.red = false;
  439. xpp.red = true;
  440. x = xpp;
  441. }
  442. else {
  443. if (x == xp.left) {
  444. root = rotateRight(root, x = xp);
  445. xpp = (xp = x.parent) == null ? null : xp.parent;
  446. }
  447. if (xp != null) {
  448. xp.red = false;
  449. if (xpp != null) {
  450. xpp.red = true;
  451. root = rotateLeft(root, xpp);
  452. }
  453. }
  454. }
  455. }
  456. }
  457. }
  458. static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
  459. TreeNode<K,V> x) {
  460. for (TreeNode<K,V> xp, xpl, xpr;;) {
  461. if (x == null || x == root)
  462. return root;
  463. else if ((xp = x.parent) == null) {
  464. x.red = false;
  465. return x;
  466. }
  467. else if (x.red) {
  468. x.red = false;
  469. return root;
  470. }
  471. else if ((xpl = xp.left) == x) {
  472. if ((xpr = xp.right) != null && xpr.red) {
  473. xpr.red = false;
  474. xp.red = true;
  475. root = rotateLeft(root, xp);
  476. xpr = (xp = x.parent) == null ? null : xp.right;
  477. }
  478. if (xpr == null)
  479. x = xp;
  480. else {
  481. TreeNode<K,V> sl = xpr.left, sr = xpr.right;
  482. if ((sr == null || !sr.red) &&
  483. (sl == null || !sl.red)) {
  484. xpr.red = true;
  485. x = xp;
  486. }
  487. else {
  488. if (sr == null || !sr.red) {
  489. if (sl != null)
  490. sl.red = false;
  491. xpr.red = true;
  492. root = rotateRight(root, xpr);
  493. xpr = (xp = x.parent) == null ?
  494. null : xp.right;
  495. }
  496. if (xpr != null) {
  497. xpr.red = (xp == null) ? false : xp.red;
  498. if ((sr = xpr.right) != null)
  499. sr.red = false;
  500. }
  501. if (xp != null) {
  502. xp.red = false;
  503. root = rotateLeft(root, xp);
  504. }
  505. x = root;
  506. }
  507. }
  508. }
  509. else { // symmetric
  510. if (xpl != null && xpl.red) {
  511. xpl.red = false;
  512. xp.red = true;
  513. root = rotateRight(root, xp);
  514. xpl = (xp = x.parent) == null ? null : xp.left;
  515. }
  516. if (xpl == null)
  517. x = xp;
  518. else {
  519. TreeNode<K,V> sl = xpl.left, sr = xpl.right;
  520. if ((sl == null || !sl.red) &&
  521. (sr == null || !sr.red)) {
  522. xpl.red = true;
  523. x = xp;
  524. }
  525. else {
  526. if (sl == null || !sl.red) {
  527. if (sr != null)
  528. sr.red = false;
  529. xpl.red = true;
  530. root = rotateLeft(root, xpl);
  531. xpl = (xp = x.parent) == null ?
  532. null : xp.left;
  533. }
  534. if (xpl != null) {
  535. xpl.red = (xp == null) ? false : xp.red;
  536. if ((sl = xpl.left) != null)
  537. sl.red = false;
  538. }
  539. if (xp != null) {
  540. xp.red = false;
  541. root = rotateRight(root, xp);
  542. }
  543. x = root;
  544. }
  545. }
  546. }
  547. }
  548. }
  549. /**
  550. * Recursive invariant check
  551. */
  552. static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
  553. TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
  554. tb = t.prev, tn = (TreeNode<K,V>)t.next;
  555. if (tb != null && tb.next != t)
  556. return false;
  557. if (tn != null && tn.prev != t)
  558. return false;
  559. if (tp != null && t != tp.left && t != tp.right)
  560. return false;
  561. if (tl != null && (tl.parent != t || tl.hash > t.hash))
  562. return false;
  563. if (tr != null && (tr.parent != t || tr.hash < t.hash))
  564. return false;
  565. if (t.red && tl != null && tl.red && tr != null && tr.red)
  566. return false;
  567. if (tl != null && !checkInvariants(tl))
  568. return false;
  569. if (tr != null && !checkInvariants(tr))
  570. return false;
  571. return true;
  572. }
  573. }

为什么要用红黑树来替代双向连表?

当然是为了效率,其实树本身就是链表的二维展开,而在HashMap的实现里,链表就是为了解决Hash冲突而诞生的,当HashMap中插入大量元素,Hash冲突的概率提高,每个桶(数组的节点)上的链表就会很大,链表查询的时间复杂度是O()(n)的.插入和删除的时间复杂度是n(1)
所以使用红黑树来替代双向链表,这样就能将查询的时间复杂度降为O(logn)的级别

红黑树是什么树?

这就延伸出另外一个问题:为什么红黑树的查询复杂度是O(logN)?

因为红黑树本身上是一颗近似平衡二叉搜索树。
二叉搜搜索树的性质定义:
1.任意一个节点,它的左子树的所有结点都要小于这个根结点
2.它的右子树的所有结点都要大于根结点
3.且对于它的任何子树都要满足这样的特性
image.png

1.基于这样的特性,二叉搜索树查询.插入,删除的操作都是O(log2N)级别的时间复杂度,N是树的节点树.也就是说,二叉搜索树的时间复杂度只和树的高度有关(树的层级)

2.二叉搜索树的中序遍历就是升序排序

2.但是会有一种极端的情况,就是所有的子结点都在左(右)边,这样的话,二叉搜索树就退化成了一个双向链表,时间复杂度也变0(N),为了维持查询的高效率,我们需要把这个二叉搜索树折叠一下,变成V字型。这个过程我们把它叫做旋,左旋,右旋,左右旋,右左旋.

image.png

通过1,2两个理论我们可以推导出,要满足二叉搜索树查询的高效率.树的左右子树需要保持平衡,这里就延伸出了平衡二叉树的概念.

https://en.wikipedia.org/wiki/Self-balancing_binary_search_tree

平衡二叉树有很多种

常见的就是AVL,红黑树,B+树

AVL树
AVL树是最早被发明的自平衡二叉查找树。在AVL树中,任一节点对应的两棵子树的最大高度差为1,因此它也被称为高度平衡树。查找、插入和删除在平均和最坏情况下的时间复杂度都是O(log {n})增加和删除元素的操作则可能需要借由一次或多次树旋转,以实现树的重新平衡。

即Balance Factor(平衡因子)是它左子树减去右子树的高度在{-1,0,1}之间
通过旋转操作来自平衡,由于要保证高度平衡所以需要更多的旋转操作

红黑树的定义
(1)节点是红色或黑色。
(2)根节点是黑色。
(3)每个叶节点(NIL节点,空节点)是黑色的。
(4)每个红色节点的两个子节点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色节点)
(5)从任一节点到其每个叶子的所有路径都包含相同数目的黑色节点。

根据定义可以保证这颗树的大概平衡,不会很偏移,需要的操作就比较少,同时保证了时间复杂度不会从O(logN)向O(N)退化.

重点-HashMap(int initialCapacity)构造方法

判断传入的初始容量和装载因子是否合法,并计算扩容门槛,扩容门槛为传入的初始容量往上取最近的2的n次方。

  1. public HashMap(int initialCapacity, float loadFactor) {
  2. // 检查传入的初始容量是否合法
  3. if (initialCapacity < 0)
  4. throw new IllegalArgumentException("Illegal initial capacity: " +
  5. initialCapacity);
  6. if (initialCapacity > MAXIMUM_CAPACITY)
  7. initialCapacity = MAXIMUM_CAPACITY;
  8. // 检查装载因子是否合法
  9. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  10. throw new IllegalArgumentException("Illegal load factor: " +
  11. loadFactor);
  12. this.loadFactor = loadFactor;
  13. // 计算扩容门槛
  14. this.threshold = tableSizeFor(initialCapacity);
  15. }
  16. static final int tableSizeFor(int cap) {
  17. // 扩容门槛为传入的初始容量往上取最近的2的n次方
  18. int n = cap - 1;
  19. n |= n >>> 1;
  20. n |= n >>> 2;
  21. n |= n >>> 4;
  22. n |= n >>> 8;
  23. n |= n >>> 16;
  24. return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  25. }
  26. 复制代码

重点-put(K key, V value)方法

添加元素的入口。

  1. public V put(K key, V value) {
  2. // 调用hash(key)计算出key的hash值
  3. return putVal(hash(key), key, value, false, true);
  4. }
  5. static final int hash(Object key) {
  6. int h;
  7. // 如果key为null,则hash值为0,否则调用key的hashCode()方法
  8. // 并让高16位与整个hash异或,这样做是为了使计算出的hash更分散
  9. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  10. }
  11. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  12. boolean evict) {
  13. Node<K, V>[] tab;
  14. Node<K, V> p;
  15. int n, i;
  16. // 如果桶的数量为0,则初始化
  17. if ((tab = table) == null || (n = tab.length) == 0)
  18. // 调用resize()初始化
  19. n = (tab = resize()).length;
  20. // (n - 1) & hash 计算元素在哪个桶中
  21. // 如果这个桶中还没有元素,则把这个元素放在桶中的第一个位置
  22. if ((p = tab[i = (n - 1) & hash]) == null)
  23. // 新建一个节点放在桶中
  24. tab[i] = newNode(hash, key, value, null);
  25. else {
  26. // 如果桶中已经有元素存在了
  27. Node<K, V> e;
  28. K k;
  29. // 如果桶中第一个元素的key与待插入元素的key相同,保存到e中用于后续修改value值
  30. if (p.hash == hash &&
  31. ((k = p.key) == key || (key != null && key.equals(k))))
  32. e = p;
  33. else if (p instanceof TreeNode)
  34. // 如果第一个元素是树节点,则调用树节点的putTreeVal插入元素
  35. e = ((TreeNode<K, V>) p).putTreeVal(this, tab, hash, key, value);
  36. else {
  37. // 遍历这个桶对应的链表,binCount用于存储链表中元素的个数
  38. for (int binCount = 0; ; ++binCount) {
  39. // 如果链表遍历完了都没有找到相同key的元素,说明该key对应的元素不存在,则在链表最后插入一个新节点
  40. if ((e = p.next) == null) {
  41. p.next = newNode(hash, key, value, null);
  42. // 如果插入新节点后链表长度大于8,则判断是否需要树化,因为第一个元素没有加到binCount中,所以这里-1
  43. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  44. treeifyBin(tab, hash);
  45. break;
  46. }
  47. // 如果待插入的key在链表中找到了,则退出循环
  48. if (e.hash == hash &&
  49. ((k = e.key) == key || (key != null && key.equals(k))))
  50. break;
  51. p = e;
  52. }
  53. }
  54. // 如果找到了对应key的元素
  55. if (e != null) { // existing mapping for key
  56. // 记录下旧值
  57. V oldValue = e.value;
  58. // 判断是否需要替换旧值
  59. if (!onlyIfAbsent || oldValue == null)
  60. // 替换旧值为新值
  61. e.value = value;
  62. // 在节点被访问后做点什么事,在LinkedHashMap中用到
  63. afterNodeAccess(e);
  64. // 返回旧值
  65. return oldValue;
  66. }
  67. }
  68. // 到这里了说明没有找到元素
  69. // 修改次数加1
  70. ++modCount;
  71. // 元素数量加1,判断是否需要扩容
  72. if (++size > threshold)
  73. // 扩容
  74. resize();
  75. // 在节点插入后做点什么事,在LinkedHashMap中用到
  76. afterNodeInsertion(evict);
  77. // 没找到元素返回null
  78. return null;
  79. }
  80. 复制代码

(1)计算key的hash值;
(2)如果桶(数组)数量为0,则初始化桶;
(3)如果key所在的桶没有元素,则直接插入;
(4)如果key所在的桶中的第一个元素的key与待插入的key相同,说明找到了元素,转后续流程(9)处理;
(5)如果
第一个元素是树节点,则调用树节点的putTreeVal()寻找元素或插入树节点;
(6)如果不是以上三种情况,则遍历桶对应的链表查找key是否存在于链表中;
(7)如果找到了对应key的元素,则转后续流程(9)处理;
(8)如果没找到对应key的元素,则在链表最后插入一个新节点并判断是否需要树化;
(9)如果找到了对应key的元素,则判断是否需要替换旧值,并直接返回旧值;
(10)如果插入了元素,则数量加1并判断是否需要扩容;

重点-resize()方法

扩容方法。

  1. final Node<K, V>[] resize() {
  2. // 旧数组
  3. Node<K, V>[] oldTab = table;
  4. // 旧容量
  5. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  6. // 旧扩容门槛
  7. int oldThr = threshold;
  8. int newCap, newThr = 0;
  9. if (oldCap > 0) {
  10. if (oldCap >= MAXIMUM_CAPACITY) {
  11. // 如果旧容量达到了最大容量,则不再进行扩容
  12. threshold = Integer.MAX_VALUE;
  13. return oldTab;
  14. } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  15. oldCap >= DEFAULT_INITIAL_CAPACITY)
  16. // 如果旧容量的两倍小于最大容量并且旧容量大于默认初始容量(16),则容量扩大为两部,扩容门槛也扩大为两倍
  17. newThr = oldThr << 1; // double threshold
  18. } else if (oldThr > 0) // initial capacity was placed in threshold
  19. // 使用非默认构造方法创建的map,第一次插入元素会走到这里
  20. // 如果旧容量为0且旧扩容门槛大于0,则把新容量赋值为旧门槛
  21. newCap = oldThr;
  22. else { // zero initial threshold signifies using defaults
  23. // 调用默认构造方法创建的map,第一次插入元素会走到这里
  24. // 如果旧容量旧扩容门槛都是0,说明还未初始化过,则初始化容量为默认容量,扩容门槛为默认容量*默认装载因子
  25. newCap = DEFAULT_INITIAL_CAPACITY;
  26. newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  27. }
  28. if (newThr == 0) {
  29. // 如果新扩容门槛为0,则计算为容量*装载因子,但不能超过最大容量
  30. float ft = (float) newCap * loadFactor;
  31. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float) MAXIMUM_CAPACITY ?
  32. (int) ft : Integer.MAX_VALUE);
  33. }
  34. // 赋值扩容门槛为新门槛
  35. threshold = newThr;
  36. // 新建一个新容量的数组
  37. @SuppressWarnings({"rawtypes", "unchecked"})
  38. Node<K, V>[] newTab = (Node<K, V>[]) new Node[newCap];
  39. // 把桶赋值为新数组
  40. table = newTab;
  41. // 如果旧数组不为空,则搬移元素
  42. if (oldTab != null) {
  43. // 遍历旧数组
  44. for (int j = 0; j < oldCap; ++j) {
  45. Node<K, V> e;
  46. // 如果桶中第一个元素不为空,赋值给e
  47. if ((e = oldTab[j]) != null) {
  48. // 清空旧桶,便于GC回收
  49. oldTab[j] = null;
  50. // 如果这个桶中只有一个元素,则计算它在新桶中的位置并把它搬移到新桶中
  51. // 因为每次都扩容两倍,所以这里的第一个元素搬移到新桶的时候新桶肯定还没有元素
  52. if (e.next == null)
  53. newTab[e.hash & (newCap - 1)] = e;
  54. else if (e instanceof TreeNode)
  55. // 如果第一个元素是树节点,则把这颗树打散成两颗树插入到新桶中去
  56. ((TreeNode<K, V>) e).split(this, newTab, j, oldCap);
  57. else { // preserve order
  58. // 如果这个链表不止一个元素且不是一颗树
  59. // 则分化成两个链表插入到新的桶中去
  60. // 比如,假如原来容量为4,3、7、11、15这四个元素都在三号桶中
  61. // 现在扩容到8,则3和11还是在三号桶,7和15要搬移到七号桶中去
  62. // 也就是分化成了两个链表
  63. Node<K, V> loHead = null, loTail = null;
  64. Node<K, V> hiHead = null, hiTail = null;
  65. Node<K, V> next;
  66. do {
  67. next = e.next;
  68. // (e.hash & oldCap) == 0的元素放在低位链表中
  69. // 比如,3 & 4 == 0
  70. if ((e.hash & oldCap) == 0) {
  71. if (loTail == null)
  72. loHead = e;
  73. else
  74. loTail.next = e;
  75. loTail = e;
  76. } else {
  77. // (e.hash & oldCap) != 0的元素放在高位链表中
  78. // 比如,7 & 4 != 0
  79. if (hiTail == null)
  80. hiHead = e;
  81. else
  82. hiTail.next = e;
  83. hiTail = e;
  84. }
  85. } while ((e = next) != null);
  86. // 遍历完成分化成两个链表了
  87. // 低位链表在新桶中的位置与旧桶一样(即3和11还在三号桶中)
  88. if (loTail != null) {
  89. loTail.next = null;
  90. newTab[j] = loHead;
  91. }
  92. // 高位链表在新桶中的位置正好是原来的位置加上旧容量(即7和15搬移到七号桶了)
  93. if (hiTail != null) {
  94. hiTail.next = null;
  95. newTab[j + oldCap] = hiHead;
  96. }
  97. }
  98. }
  99. }
  100. }
  101. return newTab;
  102. }
  103. 复制代码

(1)如果使用是默认构造方法,则第一次插入元素时初始化为默认值,容量为16,扩容门槛为12;
(2)如果使用的是非默认构造方法,则第一次插入元素时初始化容量等于扩容门槛,扩容门槛在构造方法里等于传入容量向上最近的2的n次方;
(3)如果旧容量大于0,则新容量等于旧容量的2倍,但不超过最大容量2的30次方,新扩容门槛为旧扩容门槛的2倍;
(4)创建一个新容量的桶;
(5)搬移元素,原链表分化成两个链表,低位链表存储在原来桶的位置,高位链表搬移到原来桶的位置加旧容量的位置;

TreeNode.putTreeVal(…)方法

插入元素到红黑树中的方法。

  1. final TreeNode<K, V> putTreeVal(HashMap<K, V> map, Node<K, V>[] tab,
  2. int h, K k, V v) {
  3. Class<?> kc = null;
  4. // 标记是否找到这个key的节点
  5. boolean searched = false;
  6. // 找到树的根节点
  7. TreeNode<K, V> root = (parent != null) ? root() : this;
  8. // 从树的根节点开始遍历
  9. for (TreeNode<K, V> p = root; ; ) {
  10. // dir=direction,标记是在左边还是右边
  11. // ph=p.hash,当前节点的hash值
  12. int dir, ph;
  13. // pk=p.key,当前节点的key值
  14. K pk;
  15. if ((ph = p.hash) > h) {
  16. // 当前hash比目标hash大,说明在左边
  17. dir = -1;
  18. }
  19. else if (ph < h)
  20. // 当前hash比目标hash小,说明在右边
  21. dir = 1;
  22. else if ((pk = p.key) == k || (k != null && k.equals(pk)))
  23. // 两者hash相同且key相等,说明找到了节点,直接返回该节点
  24. // 回到putVal()中判断是否需要修改其value值
  25. return p;
  26. else if ((kc == null &&
  27. // 如果k是Comparable的子类则返回其真实的类,否则返回null
  28. (kc = comparableClassFor(k)) == null) ||
  29. // 如果k和pk不是同样的类型则返回0,否则返回两者比较的结果
  30. (dir = compareComparables(kc, k, pk)) == 0) {
  31. // 这个条件表示两者hash相同但是其中一个不是Comparable类型或者两者类型不同
  32. // 比如key是Object类型,这时可以传String也可以传Integer,两者hash值可能相同
  33. // 在红黑树中把同样hash值的元素存储在同一颗子树,这里相当于找到了这颗子树的顶点
  34. // 从这个顶点分别遍历其左右子树去寻找有没有跟待插入的key相同的元素
  35. if (!searched) {
  36. TreeNode<K, V> q, ch;
  37. searched = true;
  38. // 遍历左右子树找到了直接返回
  39. if (((ch = p.left) != null &&
  40. (q = ch.find(h, k, kc)) != null) ||
  41. ((ch = p.right) != null &&
  42. (q = ch.find(h, k, kc)) != null))
  43. return q;
  44. }
  45. // 如果两者类型相同,再根据它们的内存地址计算hash值进行比较
  46. dir = tieBreakOrder(k, pk);
  47. }
  48. TreeNode<K, V> xp = p;
  49. if ((p = (dir <= 0) ? p.left : p.right) == null) {
  50. // 如果最后确实没找到对应key的元素,则新建一个节点
  51. Node<K, V> xpn = xp.next;
  52. TreeNode<K, V> x = map.newTreeNode(h, k, v, xpn);
  53. if (dir <= 0)
  54. xp.left = x;
  55. else
  56. xp.right = x;
  57. xp.next = x;
  58. x.parent = x.prev = xp;
  59. if (xpn != null)
  60. ((TreeNode<K, V>) xpn).prev = x;
  61. // 插入树节点后平衡
  62. // 把root节点移动到链表的第一个节点
  63. moveRootToFront(tab, balanceInsertion(root, x));
  64. return null;
  65. }
  66. }
  67. }
  68. 复制代码

(1)寻找根节点;
(2)从根节点开始查找;
(3)比较hash值及key值,如果都相同,直接返回,在putVal()方法中决定是否要替换value值;
(4)根据hash值及key值确定在树的左子树还是右子树查找,找到了直接返回;
(5)如果最后没有找到则在树的相应位置插入元素,并做平衡;

treeifyBin()方法

如果插入元素后链表的长度大于等于8则判断是否需要树化。

  1. final void treeifyBin(Node<K, V>[] tab, int hash) {
  2. int n, index;
  3. Node<K, V> e;
  4. if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
  5. // 如果桶数量小于64,直接扩容而不用树化
  6. // 因为扩容之后,链表会分化成两个链表,达到减少元素的作用
  7. // 当然也不一定,比如容量为4,里面存的全是除以4余数等于3的元素
  8. // 这样即使扩容也无法减少链表的长度
  9. resize();
  10. else if ((e = tab[index = (n - 1) & hash]) != null) {
  11. TreeNode<K, V> hd = null, tl = null;
  12. // 把所有节点换成树节点
  13. do {
  14. TreeNode<K, V> p = replacementTreeNode(e, null);
  15. if (tl == null)
  16. hd = p;
  17. else {
  18. p.prev = tl;
  19. tl.next = p;
  20. }
  21. tl = p;
  22. } while ((e = e.next) != null);
  23. // 如果进入过上面的循环,则从头节点开始树化
  24. if ((tab[index] = hd) != null)
  25. hd.treeify(tab);
  26. }
  27. }
  28. 复制代码

TreeNode.treeify()方法

真正树化的方法。

  1. final void treeify(Node<K, V>[] tab) {
  2. TreeNode<K, V> root = null;
  3. for (TreeNode<K, V> x = this, next; x != null; x = next) {
  4. next = (TreeNode<K, V>) x.next;
  5. x.left = x.right = null;
  6. // 第一个元素作为根节点且为黑节点,其它元素依次插入到树中再做平衡
  7. if (root == null) {
  8. x.parent = null;
  9. x.red = false;
  10. root = x;
  11. } else {
  12. K k = x.key;
  13. int h = x.hash;
  14. Class<?> kc = null;
  15. // 从根节点查找元素插入的位置
  16. for (TreeNode<K, V> p = root; ; ) {
  17. int dir, ph;
  18. K pk = p.key;
  19. if ((ph = p.hash) > h)
  20. dir = -1;
  21. else if (ph < h)
  22. dir = 1;
  23. else if ((kc == null &&
  24. (kc = comparableClassFor(k)) == null) ||
  25. (dir = compareComparables(kc, k, pk)) == 0)
  26. dir = tieBreakOrder(k, pk);
  27. // 如果最后没找到元素,则插入
  28. TreeNode<K, V> xp = p;
  29. if ((p = (dir <= 0) ? p.left : p.right) == null) {
  30. x.parent = xp;
  31. if (dir <= 0)
  32. xp.left = x;
  33. else
  34. xp.right = x;
  35. // 插入后平衡,默认插入的是红节点,在balanceInsertion()方法里
  36. root = balanceInsertion(root, x);
  37. break;
  38. }
  39. }
  40. }
  41. }
  42. // 把根节点移动到链表的头节点,因为经过平衡之后原来的第一个元素不一定是根节点了
  43. moveRootToFront(tab, root);
  44. }
  45. 复制代码

(1)从链表的第一个元素开始遍历;
(2)将第一个元素作为根节点;
(3)其它元素依次插入到红黑树中,再做平衡;
(4)将根节点移到链表第一元素的位置(因为平衡的时候根节点会改变);

重点-get(Object key)方法

  1. public V get(Object key) {
  2. Node<K, V> e;
  3. return (e = getNode(hash(key), key)) == null ? null : e.value;
  4. }
  5. final Node<K, V> getNode(int hash, Object key) {
  6. Node<K, V>[] tab;
  7. Node<K, V> first, e;
  8. int n;
  9. K k;
  10. // 如果桶的数量大于0并且待查找的key所在的桶的第一个元素不为空
  11. if ((tab = table) != null && (n = tab.length) > 0 &&
  12. (first = tab[(n - 1) & hash]) != null) {
  13. // 检查第一个元素是不是要查的元素,如果是直接返回
  14. if (first.hash == hash && // always check first node
  15. ((k = first.key) == key || (key != null && key.equals(k))))
  16. return first;
  17. if ((e = first.next) != null) {
  18. // 如果第一个元素是树节点,则按树的方式查找
  19. if (first instanceof TreeNode)
  20. return ((TreeNode<K, V>) first).getTreeNode(hash, key);
  21. // 否则就遍历整个链表查找该元素
  22. do {
  23. if (e.hash == hash &&
  24. ((k = e.key) == key || (key != null && key.equals(k))))
  25. return e;
  26. } while ((e = e.next) != null);
  27. }
  28. }
  29. return null;
  30. }
  31. 复制代码

(1)计算key的hash值;
(2)找到key所在的桶及其第一个元素;
(3)如果第一个元素的key等于待查找的key,直接返回;
(4)如果第一个元素是树节点就按树的方式来查找,否则按链表方式查找;

TreeNode.getTreeNode(int h, Object k)方法

  1. final TreeNode<K, V> getTreeNode(int h, Object k) {
  2. // 从树的根节点开始查找
  3. return ((parent != null) ? root() : this).find(h, k, null);
  4. }
  5. final TreeNode<K, V> find(int h, Object k, Class<?> kc) {
  6. TreeNode<K, V> p = this;
  7. do {
  8. int ph, dir;
  9. K pk;
  10. TreeNode<K, V> pl = p.left, pr = p.right, q;
  11. if ((ph = p.hash) > h)
  12. // 左子树
  13. p = pl;
  14. else if (ph < h)
  15. // 右子树
  16. p = pr;
  17. else if ((pk = p.key) == k || (k != null && k.equals(pk)))
  18. // 找到了直接返回
  19. return p;
  20. else if (pl == null)
  21. // hash相同但key不同,左子树为空查右子树
  22. p = pr;
  23. else if (pr == null)
  24. // 右子树为空查左子树
  25. p = pl;
  26. else if ((kc != null ||
  27. (kc = comparableClassFor(k)) != null) &&
  28. (dir = compareComparables(kc, k, pk)) != 0)
  29. // 通过compare方法比较key值的大小决定使用左子树还是右子树
  30. p = (dir < 0) ? pl : pr;
  31. else if ((q = pr.find(h, k, kc)) != null)
  32. // 如果以上条件都不通过,则尝试在右子树查找
  33. return q;
  34. else
  35. // 都没找到就在左子树查找
  36. p = pl;
  37. } while (p != null);
  38. return null;
  39. }
  40. 复制代码

经典二叉查找树的查找过程,先根据hash值比较,再根据key值比较决定是查左子树还是右子树。

重点-remove(Object key)方法

  1. public V remove(Object key) {
  2. Node<K, V> e;
  3. return (e = removeNode(hash(key), key, null, false, true)) == null ?
  4. null : e.value;
  5. }
  6. final Node<K, V> removeNode(int hash, Object key, Object value,
  7. boolean matchValue, boolean movable) {
  8. Node<K, V>[] tab;
  9. Node<K, V> p;
  10. int n, index;
  11. // 如果桶的数量大于0且待删除的元素所在的桶的第一个元素不为空
  12. if ((tab = table) != null && (n = tab.length) > 0 &&
  13. (p = tab[index = (n - 1) & hash]) != null) {
  14. Node<K, V> node = null, e;
  15. K k;
  16. V v;
  17. if (p.hash == hash &&
  18. ((k = p.key) == key || (key != null && key.equals(k))))
  19. // 如果第一个元素正好就是要找的元素,赋值给node变量后续删除使用
  20. node = p;
  21. else if ((e = p.next) != null) {
  22. if (p instanceof TreeNode)
  23. // 如果第一个元素是树节点,则以树的方式查找节点
  24. node = ((TreeNode<K, V>) p).getTreeNode(hash, key);
  25. else {
  26. // 否则遍历整个链表查找元素
  27. do {
  28. if (e.hash == hash &&
  29. ((k = e.key) == key ||
  30. (key != null && key.equals(k)))) {
  31. node = e;
  32. break;
  33. }
  34. p = e;
  35. } while ((e = e.next) != null);
  36. }
  37. }
  38. // 如果找到了元素,则看参数是否需要匹配value值,如果不需要匹配直接删除,如果需要匹配则看value值是否与传入的value相等
  39. if (node != null && (!matchValue || (v = node.value) == value ||
  40. (value != null && value.equals(v)))) {
  41. if (node instanceof TreeNode)
  42. // 如果是树节点,调用树的删除方法(以node调用的,是删除自己)
  43. ((TreeNode<K, V>) node).removeTreeNode(this, tab, movable);
  44. else if (node == p)
  45. // 如果待删除的元素是第一个元素,则把第二个元素移到第一的位置
  46. tab[index] = node.next;
  47. else
  48. // 否则删除node节点
  49. p.next = node.next;
  50. ++modCount;
  51. --size;
  52. // 删除节点后置处理
  53. afterNodeRemoval(node);
  54. return node;
  55. }
  56. }
  57. return null;
  58. }
  59. 复制代码

(1)先查找元素所在的节点;
(2)如果找到的节点是树节点,则按树的移除节点处理;
(3)如果找到的节点是桶中的第一个节点,则把第二个节点移到第一的位置;
(4)否则按链表删除节点处理;
(5)修改size,调用移除节点后置处理等;

TreeNode.removeTreeNode(…)方法

  1. final void removeTreeNode(HashMap<K, V> map, Node<K, V>[] tab,
  2. boolean movable) {
  3. int n;
  4. // 如果桶的数量为0直接返回
  5. if (tab == null || (n = tab.length) == 0)
  6. return;
  7. // 节点在桶中的索引
  8. int index = (n - 1) & hash;
  9. // 第一个节点,根节点,根左子节点
  10. TreeNode<K, V> first = (TreeNode<K, V>) tab[index], root = first, rl;
  11. // 后继节点,前置节点
  12. TreeNode<K, V> succ = (TreeNode<K, V>) next, pred = prev;
  13. if (pred == null)
  14. // 如果前置节点为空,说明当前节点是根节点,则把后继节点赋值到第一个节点的位置,相当于删除了当前节点
  15. tab[index] = first = succ;
  16. else
  17. // 否则把前置节点的下个节点设置为当前节点的后继节点,相当于删除了当前节点
  18. pred.next = succ;
  19. // 如果后继节点不为空,则让后继节点的前置节点指向当前节点的前置节点,相当于删除了当前节点
  20. if (succ != null)
  21. succ.prev = pred;
  22. // 如果第一个节点为空,说明没有后继节点了,直接返回
  23. if (first == null)
  24. return;
  25. // 如果根节点的父节点不为空,则重新查找父节点
  26. if (root.parent != null)
  27. root = root.root();
  28. // 如果根节点为空,则需要反树化(将树转化为链表)
  29. // 如果需要移动节点且树的高度比较小,则需要反树化
  30. if (root == null
  31. || (movable
  32. && (root.right == null
  33. || (rl = root.left) == null
  34. || rl.left == null))) {
  35. tab[index] = first.untreeify(map); // too small
  36. return;
  37. }
  38. // 分割线,以上都是删除链表中的节点,下面才是直接删除红黑树的节点(因为TreeNode本身即是链表节点又是树节点)
  39. // 删除红黑树节点的大致过程是寻找右子树中最小的节点放到删除节点的位置,然后做平衡,此处不过多注释
  40. TreeNode<K, V> p = this, pl = left, pr = right, replacement;
  41. if (pl != null && pr != null) {
  42. TreeNode<K, V> s = pr, sl;
  43. while ((sl = s.left) != null) // find successor
  44. s = sl;
  45. boolean c = s.red;
  46. s.red = p.red;
  47. p.red = c; // swap colors
  48. TreeNode<K, V> sr = s.right;
  49. TreeNode<K, V> pp = p.parent;
  50. if (s == pr) { // p was s's direct parent
  51. p.parent = s;
  52. s.right = p;
  53. } else {
  54. TreeNode<K, V> sp = s.parent;
  55. if ((p.parent = sp) != null) {
  56. if (s == sp.left)
  57. sp.left = p;
  58. else
  59. sp.right = p;
  60. }
  61. if ((s.right = pr) != null)
  62. pr.parent = s;
  63. }
  64. p.left = null;
  65. if ((p.right = sr) != null)
  66. sr.parent = p;
  67. if ((s.left = pl) != null)
  68. pl.parent = s;
  69. if ((s.parent = pp) == null)
  70. root = s;
  71. else if (p == pp.left)
  72. pp.left = s;
  73. else
  74. pp.right = s;
  75. if (sr != null)
  76. replacement = sr;
  77. else
  78. replacement = p;
  79. } else if (pl != null)
  80. replacement = pl;
  81. else if (pr != null)
  82. replacement = pr;
  83. else
  84. replacement = p;
  85. if (replacement != p) {
  86. TreeNode<K, V> pp = replacement.parent = p.parent;
  87. if (pp == null)
  88. root = replacement;
  89. else if (p == pp.left)
  90. pp.left = replacement;
  91. else
  92. pp.right = replacement;
  93. p.left = p.right = p.parent = null;
  94. }
  95. TreeNode<K, V> r = p.red ? root : balanceDeletion(root, replacement);
  96. if (replacement == p) { // detach
  97. TreeNode<K, V> pp = p.parent;
  98. p.parent = null;
  99. if (pp != null) {
  100. if (p == pp.left)
  101. pp.left = null;
  102. else if (p == pp.right)
  103. pp.right = null;
  104. }
  105. }
  106. if (movable)
  107. moveRootToFront(tab, r);
  108. }
  109. 复制代码

(1)TreeNode本身既是链表节点也是红黑树节点;
(2)先删除链表节点;
(3)再删除红黑树节点并做平衡;

总结

(1)HashMap是一种散列表,采用(数组 + 链表 + 红黑树)的存储结构;
(2)HashMap的默认初始容量为16(1<<4),默认装载因子为0.75f,容量总是2的n次方;
(3)HashMap扩容时每次容量变为原来的两倍;
(4)当桶的数量小于64时不会进行树化,只会扩容;
(5)当桶的数量大于64且单个桶中元素的数量大于8时,进行树化;
(6)当单个桶中元素数量小于6时,进行反树化;
(7)HashMap是非线程安全的容器;
(8)HashMap查找添加元素的时间复杂度都为O(1);

ArrayList源码

简介

ArrayList是一种以数组实现的List,与数组相比,它具有动态扩展的能力,因此也可称之为动态数组。

继承体系

Java基础-容器 - 图6
ArrayList实现了List, RandomAccess, Cloneable, java.io.Serializable等接口。
ArrayList实现了List,提供了基础的添加、删除、遍历等操作。
ArrayList实现了RandomAccess,提供了随机访问的能力。
ArrayList实现了Cloneable,可以被克隆。
ArrayList实现了Serializable,可以被序列化。

源码解析

属性

  1. /**
  2. * 默认容量
  3. */
  4. private static final int DEFAULT_CAPACITY = 10;
  5. /**
  6. * 空数组,如果传入的容量为0时使用
  7. */
  8. private static final Object[] EMPTY_ELEMENTDATA = {};
  9. /**
  10. * 空数组,传传入容量时使用,添加第一个元素的时候会重新初始为默认容量大小
  11. */
  12. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  13. /**
  14. * 存储元素的数组,本文由公从号“彤哥读源码”原创
  15. */
  16. transient Object[] elementData; // non-private to simplify nested class access
  17. /**
  18. * 集合中元素的个数
  19. */
  20. private int size;
  21. 复制代码

(1)DEFAULT_CAPACITY
默认容量为10,也就是通过new ArrayList()创建时的默认容量。
(2)EMPTY_ELEMENTDATA
空的数组,这种是通过new ArrayList(0)创建时用的是这个空数组。
(3)DEFAULTCAPACITY_EMPTY_ELEMENTDATA
也是空数组,这种是通过new ArrayList()创建时用的是这个空数组,与EMPTY_ELEMENTDATA的区别是在添加第一个元素时使用这个空数组的会初始化为DEFAULT_CAPACITY(10)个元素。
(4)elementData
真正存放元素的地方,使用transient是为了不序列化这个字段。
至于没有使用private修饰,后面注释是写的“为了简化嵌套类的访问”,但是楼主实测加了private嵌套类一样可以访问。
private表示是类私有的属性,只要是在这个类内部都可以访问,嵌套类或者内部类也是在类的内部,所以也可以访问类的私有成员。
(5)size
真正存储元素的个数,而不是elementData数组的长度。

ArrayList(int initialCapacity)构造方法

传入初始容量,如果大于0就初始化elementData为对应大小,如果等于0就使用EMPTY_ELEMENTDATA空数组,如果小于0抛出异常。

  1. public ArrayList(int initialCapacity) {
  2. if (initialCapacity > 0) {
  3. // 如果传入的初始容量大于0,就新建一个数组存储元素
  4. this.elementData = new Object[initialCapacity];
  5. } else if (initialCapacity == 0) {
  6. // 如果传入的初始容量等于0,使用空数组EMPTY_ELEMENTDATA
  7. this.elementData = EMPTY_ELEMENTDATA;
  8. } else {
  9. // 如果传入的初始容量小于0,抛出异常
  10. throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
  11. }
  12. }
  13. 复制代码

ArrayList()构造方法

不传初始容量,初始化为DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组,会在添加第一个元素的时候扩容为默认的大小,即10。

  1. public ArrayList() {
  2. // 如果没有传入初始容量,则使用空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA
  3. // 使用这个数组是在添加第一个元素的时候会扩容到默认大小10
  4. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  5. }
  6. 复制代码

ArrayList(Collection<? extends E> c)构造方法

传入集合并初始化elementData,这里会使用拷贝把传入集合的元素拷贝到elementData数组中,如果元素个数为0,则初始化为EMPTY_ELEMENTDATA空数组。

  1. /**
  2. * 把传入集合的元素初始化到ArrayList中
  3. */
  4. public ArrayList(Collection<? extends E> c) {
  5. // 集合转数组
  6. elementData = c.toArray();
  7. if ((size = elementData.length) != 0) {
  8. // 检查c.toArray()返回的是不是Object[]类型,如果不是,重新拷贝成Object[].class类型
  9. if (elementData.getClass() != Object[].class)
  10. elementData = Arrays.copyOf(elementData, size, Object[].class);
  11. } else {
  12. // 如果c的空集合,则初始化为空数组EMPTY_ELEMENTDATA
  13. this.elementData = EMPTY_ELEMENTDATA;
  14. }
  15. }
  16. 复制代码

为什么c.toArray();返回的有可能不是Object[]类型呢?请看下面的代码:

  1. public class ArrayTest {
  2. public static void main(String[] args) {
  3. Father[] fathers = new Son[]{};
  4. // 打印结果为class [Lcom.coolcoding.code.Son;
  5. System.out.println(fathers.getClass());
  6. List<String> strList = new MyList();
  7. // 打印结果为class [Ljava.lang.String;
  8. //,本文由公从号“彤哥读源码”原创
  9. System.out.println(strList.toArray().getClass());
  10. }
  11. }
  12. class Father {}
  13. class Son extends Father {}
  14. class MyList extends ArrayList<String> {
  15. /**
  16. * 子类重写父类的方法,返回值可以不一样
  17. * 但这里只能用数组类型,换成Object就不行
  18. * 应该算是java本身的bug
  19. */
  20. @Override
  21. public String[] toArray() {
  22. // 为了方便举例直接写死
  23. return new String[]{"1", "2", "3"};
  24. }
  25. }
  26. 复制代码

add(E e)方法

添加元素到末尾,平均时间复杂度为O(1)。

  1. public boolean add(E e) {
  2. // 检查是否需要扩容
  3. ensureCapacityInternal(size + 1);
  4. // 把元素插入到最后一位
  5. elementData[size++] = e;
  6. return true;
  7. }
  8. private void ensureCapacityInternal(int minCapacity) {
  9. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
  10. }
  11. private static int calculateCapacity(Object[] elementData, int minCapacity) {
  12. // 如果是空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA,就初始化为默认大小10
  13. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  14. return Math.max(DEFAULT_CAPACITY, minCapacity);
  15. }
  16. return minCapacity;
  17. }
  18. private void ensureExplicitCapacity(int minCapacity) {
  19. modCount++;
  20. if (minCapacity - elementData.length > 0)
  21. // 扩容
  22. grow(minCapacity);
  23. }
  24. private void grow(int minCapacity) {
  25. int oldCapacity = elementData.length;
  26. // 新容量为旧容量的1.5倍
  27. int newCapacity = oldCapacity + (oldCapacity >> 1);
  28. // 如果新容量发现比需要的容量还小,则以需要的容量为准
  29. if (newCapacity - minCapacity < 0)
  30. newCapacity = minCapacity;
  31. // 如果新容量已经超过最大容量了,则使用最大容量
  32. if (newCapacity - MAX_ARRAY_SIZE > 0)
  33. newCapacity = hugeCapacity(minCapacity);
  34. // 以新容量拷贝出来一个新数组
  35. elementData = Arrays.copyOf(elementData, newCapacity);
  36. }
  37. 复制代码

(1)检查是否需要扩容;
(2)如果elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA则初始化容量大小为DEFAULT_CAPACITY;
(3)新容量是老容量的1.5倍(oldCapacity + (oldCapacity >> 1)),如果加了这么多容量发现比需要的容量还小,则以需要的容量为准;
(4)创建新容量的数组并把老数组拷贝到新数组;

add(int index, E element)方法

添加元素到指定位置,平均时间复杂度为O(n)。

  1. public void add(int index, E element) {
  2. // 检查是否越界
  3. rangeCheckForAdd(index);
  4. // 检查是否需要扩容
  5. ensureCapacityInternal(size + 1);
  6. // 将inex及其之后的元素往后挪一位,则index位置处就空出来了
  7. System.arraycopy(elementData, index, elementData, index + 1,
  8. size - index);
  9. // 将元素插入到index的位置
  10. elementData[index] = element;
  11. // 大小增1
  12. size++;
  13. }
  14. private void rangeCheckForAdd(int index) {
  15. if (index > size || index < 0)
  16. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  17. }
  18. 复制代码

(1)检查索引是否越界;
(2)检查是否需要扩容;
(3)把插入索引位置后的元素都往后挪一位;
(4)在插入索引位置放置插入的元素;
(5)大小加1;

addAll(Collection<? extends E> c)方法

求两个集合的并集。

  1. /**
  2. * 将集合c中所有元素添加到当前ArrayList中
  3. */
  4. public boolean addAll(Collection<? extends E> c) {
  5. // 将集合c转为数组
  6. Object[] a = c.toArray();
  7. int numNew = a.length;
  8. // 检查是否需要扩容
  9. ensureCapacityInternal(size + numNew);
  10. // 将c中元素全部拷贝到数组的最后
  11. System.arraycopy(a, 0, elementData, size, numNew);
  12. // 大小增加c的大小
  13. size += numNew;
  14. // 如果c不为空就返回true,否则返回false
  15. return numNew != 0;
  16. }
  17. 复制代码

(1)拷贝c中的元素到数组a中;
(2)检查是否需要扩容;
(3)把数组a中的元素拷贝到elementData的尾部;

get(int index)方法

获取指定索引位置的元素,时间复杂度为O(1)。

  1. public E get(int index) {
  2. // 检查是否越界
  3. rangeCheck(index);
  4. // 返回数组index位置的元素
  5. return elementData(index);
  6. }
  7. private void rangeCheck(int index) {
  8. if (index >= size)
  9. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  10. }
  11. E elementData(int index) {
  12. return (E) elementData[index];
  13. }
  14. 复制代码

(1)检查索引是否越界,这里只检查是否越上界,如果越上界抛出IndexOutOfBoundsException异常,如果越下界抛出的是ArrayIndexOutOfBoundsException异常。
(2)返回索引位置处的元素;

remove(int index)方法

删除指定索引位置的元素,时间复杂度为O(n)。

  1. public E remove(int index) {
  2. // 检查是否越界
  3. rangeCheck(index);
  4. modCount++;
  5. // 获取index位置的元素
  6. E oldValue = elementData(index);
  7. // 如果index不是最后一位,则将index之后的元素往前挪一位
  8. int numMoved = size - index - 1;
  9. if (numMoved > 0)
  10. System.arraycopy(elementData, index+1, elementData, index, numMoved);
  11. // 将最后一个元素删除,帮助GC
  12. elementData[--size] = null; // clear to let GC do its work
  13. // 返回旧值
  14. return oldValue;
  15. }
  16. 复制代码

(1)检查索引是否越界;
(2)获取指定索引位置的元素;
(3)如果删除的不是最后一位,则其它元素往前移一位;
(4)将最后一位置为null,方便GC回收;
(5)返回删除的元素,本文由公从号“彤哥读源码”原创。
可以看到,ArrayList删除元素的时候并没有缩容。

remove(Object o)方法

删除指定元素值的元素,时间复杂度为O(n)。

  1. public boolean remove(Object o) {
  2. if (o == null) {
  3. // 遍历整个数组,找到元素第一次出现的位置,并将其快速删除
  4. for (int index = 0; index < size; index++)
  5. // 如果要删除的元素为null,则以null进行比较,使用==
  6. if (elementData[index] == null) {
  7. fastRemove(index);
  8. return true;
  9. }
  10. } else {
  11. // 遍历整个数组,找到元素第一次出现的位置,并将其快速删除
  12. for (int index = 0; index < size; index++)
  13. // 如果要删除的元素不为null,则进行比较,使用equals()方法
  14. if (o.equals(elementData[index])) {
  15. fastRemove(index);
  16. return true;
  17. }
  18. }
  19. return false;
  20. }
  21. private void fastRemove(int index) {
  22. // 少了一个越界的检查
  23. modCount++;
  24. // 如果index不是最后一位,则将index之后的元素往前挪一位
  25. int numMoved = size - index - 1;
  26. if (numMoved > 0)
  27. System.arraycopy(elementData, index+1, elementData, index, numMoved);
  28. // 将最后一个元素删除,帮助GC
  29. elementData[--size] = null; // clear to let GC do its work
  30. }
  31. 复制代码

(1)找到第一个等于指定元素值的元素;
(2)快速删除;
fastRemove(int index)相对于remove(int index)少了检查索引越界的操作,可见jdk将性能优化到极致。

retainAll(Collection<?> c)方法

求两个集合的交集。

  1. public boolean retainAll(Collection<?> c) {
  2. // 集合c不能为null
  3. Objects.requireNonNull(c);
  4. // 调用批量删除方法,这时complement传入true,表示删除不包含在c中的元素
  5. return batchRemove(c, true);
  6. }
  7. /**
  8. * 批量删除元素
  9. * complement为true表示删除c中不包含的元素
  10. * complement为false表示删除c中包含的元素
  11. */
  12. private boolean batchRemove(Collection<?> c, boolean complement) {
  13. final Object[] elementData = this.elementData;
  14. // 使用读写两个指针同时遍历数组
  15. // 读指针每次自增1,写指针放入元素的时候才加1
  16. // 这样不需要额外的空间,只需要在原有的数组上操作就可以了
  17. int r = 0, w = 0;
  18. boolean modified = false;
  19. try {
  20. // 遍历整个数组,如果c中包含该元素,则把该元素放到写指针的位置(以complement为准)
  21. for (; r < size; r++)
  22. if (c.contains(elementData[r]) == complement)
  23. elementData[w++] = elementData[r];
  24. } finally {
  25. // 正常来说r最后是等于size的,除非c.contains()抛出了异常
  26. if (r != size) {
  27. // 如果c.contains()抛出了异常,则把未读的元素都拷贝到写指针之后
  28. System.arraycopy(elementData, r,
  29. elementData, w,
  30. size - r);
  31. w += size - r;
  32. }
  33. if (w != size) {
  34. // 将写指针之后的元素置为空,帮助GC
  35. for (int i = w; i < size; i++)
  36. elementData[i] = null;
  37. modCount += size - w;
  38. // 新大小等于写指针的位置(因为每写一次写指针就加1,所以新大小正好等于写指针的位置)
  39. size = w;
  40. modified = true;
  41. }
  42. }
  43. // 有修改返回true
  44. return modified;
  45. }
  46. 复制代码

(1)遍历elementData数组;
(2)如果元素在c中,则把这个元素添加到elementData数组的w位置并将w位置往后移一位;
(3)遍历完之后,w之前的元素都是两者共有的,w之后(包含)的元素不是两者共有的;
(4)将w之后(包含)的元素置为null,方便GC回收;

removeAll(Collection<?> c)

求两个集合的单方向差集,只保留当前集合中不在c中的元素,不保留在c中不在当前集体中的元素。

  1. public boolean removeAll(Collection<?> c) {
  2. // 集合c不能为空
  3. Objects.requireNonNull(c);
  4. // 同样调用批量删除方法,这时complement传入false,表示删除包含在c中的元素
  5. return batchRemove(c, false);
  6. }
  7. 复制代码

与retainAll(Collection<?> c)方法类似,只是这里保留的是不在c中的元素。

总结

(1)ArrayList内部使用数组存储元素,当数组长度不够时进行扩容,每次加一半的空间,ArrayList不会进行缩容;
(2)ArrayList支持随机访问,通过索引访问元素极快,时间复杂度为O(1);
(3)ArrayList添加元素到尾部极快,平均时间复杂度为O(1);
(4)ArrayList添加元素到中间比较慢,因为要搬移元素,平均时间复杂度为O(n);
(5)ArrayList从尾部删除元素极快,时间复杂度为O(1);
(6)ArrayList从中间删除元素比较慢,因为要搬移元素,平均时间复杂度为O(n);
(7)ArrayList支持求并集,调用addAll(Collection<? extends E> c)方法即可;
(8)ArrayList支持求交集,调用retainAll(Collection<? extends E> c)方法即可;
(7)ArrayList支持求单向差集,调用removeAll(Collection<? extends E> c)方法即可;

彩蛋

elementData设置成了transient,那ArrayList是怎么把元素序列化的呢?

  1. private void writeObject(java.io.ObjectOutputStream s)
  2. throws java.io.IOException{
  3. // 防止序列化期间有修改
  4. int expectedModCount = modCount;
  5. // 写出非transient非static属性(会写出size属性)
  6. s.defaultWriteObject();
  7. // 写出元素个数
  8. s.writeInt(size);
  9. // 依次写出元素
  10. for (int i=0; i<size; i++) {
  11. s.writeObject(elementData[i]);
  12. }
  13. // 如果有修改,抛出异常,本文由公从号“彤哥读源码”原创
  14. if (modCount != expectedModCount) {
  15. throw new ConcurrentModificationException();
  16. }
  17. }
  18. private void readObject(java.io.ObjectInputStream s)
  19. throws java.io.IOException, ClassNotFoundException {
  20. // 声明为空数组
  21. elementData = EMPTY_ELEMENTDATA;
  22. // 读入非transient非static属性(会读取size属性)
  23. s.defaultReadObject();
  24. // 读入元素个数,没什么用,只是因为写出的时候写了size属性,读的时候也要按顺序来读
  25. s.readInt();
  26. if (size > 0) {
  27. // 计算容量
  28. int capacity = calculateCapacity(elementData, size);
  29. SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
  30. // 检查是否需要扩容
  31. ensureCapacityInternal(size);
  32. Object[] a = elementData;
  33. // 依次读取元素到数组中
  34. for (int i=0; i<size; i++) {
  35. a[i] = s.readObject();
  36. }
  37. }
  38. }
  39. 复制代码

查看writeObject()方法可知,先调用s.defaultWriteObject()方法,再把size写入到流中,再把元素一个一个的写入到流中。
一般地,只要实现了Serializable接口即可自动序列化,writeObject()和readObject()是为了自己控制序列化的方式,这两个方法必须声明为private,在java.io.ObjectStreamClass#getPrivateMethod()方法中通过反射获取到writeObject()这个方法。
在ArrayList的writeObject()方法中先调用了s.defaultWriteObject()方法,这个方法是写入非static非transient的属性,在ArrayList中也就是size属性。同样地,在readObject()方法中先调用了s.defaultReadObject()方法解析出了size属性。
elementData定义为transient的优势,自己根据size序列化真实的元素,而不是根据数组的长度序列化元素,减少了空间占用。


作者:彤哥读源码
链接:https://juejin.im/post/6866301216989642765
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Java集合常见面试题搜集

https://github.com/Snailclimb/JavaGuide/blob/master/docs/java/collection/Java%E9%9B%86%E5%90%88%E6%A1%86%E6%9E%B6%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95%E9%A2%98.md