Collection接口

在java的集合类库中,基本接口是Collection,该接口的在集合中的源码定义如下(将源码中的注释删掉了):

  1. public interface Collection<E> extends Iterable<E> {
  2. // Query Operations
  3. // 查询操作相关方法
  4.  
  5. // 返回集合的元素个数
  6. int size();
  7.  
  8. // 如果这个集合没有包含任何元素了就返回true,即判断集合是否为空
  9. boolean isEmpty();
  10.  
  11. // 如果这个集合至少包含一个指定的元素就返回true,
  12. //如果指定的元素和集合中的元素不兼容,会抛出 ClassCastException
  13. // 如果指定的元素为空并且该集合不允许元素为空时,会抛出 NullPointerException
  14. boolean contains(Object o);
  15.  
  16. // 返回集合中元素的迭代器,它不保证元素的有序性 (除非该集合本身的实现可以保证元素的顺序)
  17. Iterator<E> iterator();
  18.  
  19. // 返回一个包含集合中所有元素的数组,元素的顺序性和 iterator 一样,由集合实现类本身决定
  20. // 这个方法返回的数组时安全的,因为集合不用保留对返回数组的引用,我们可以任意修改而不影响集合本身
  21. Object[] toArray();
  22.  
  23. // 返回包含该集合中所有元素的数组,数组的运行时类型是指定数组的类型,
  24. // 如果指定的数组适合集合的大小,直接返回其中,否则重新创建数组
  25. <T> T[] toArray(T[] a);
  26.  
  27. // Modification Operations
  28.  
  29. // 往集合中添加一个元素,如果集合允许更改就返回true,如果集合不允许元素重复并且已经包含了此元素,则返回false
  30. boolean add(E e);
  31.  
  32. // 从集合中删除指定元素的单个实例 如果集合允许改变就返回true
  33. boolean remove(Object o);
  34.  
  35. // Bulk Operations
  36. // 批量操作相关
  37.  
  38. // 如果该集合包含指定集合的所有元素 则返回true
  39. boolean containsAll(Collection<?> c);
  40.  
  41. // 添加指定集合的所有元素到该集合中
  42. // 如果在添加操作的过程中修改了指定的集合 ,则此操作的行为是不确定的,不安全
  43. boolean addAll(Collection<? extends E> c);
  44.  
  45. // 在该集合中删除指定集合的所有元素,反方法成功返回后,该集合中将不再包含任何指定集合中的元素
  46. boolean removeAll(Collection<?> c);
  47.  
  48. // 删除满足给定条件的所有元素,如果在迭代期间发生运行时异常,那么将返回给调用者
  49. // 注意:这是JDK1.8 的新特性,在接口中也有方法实现,实现类调用时的默认实现逻辑
  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.  
  63. // 从集合中删除不包含在指定集合中的所有元素
  64. boolean retainAll(Collection<?> c);
  65.  
  66. // 清空集合中的所有元素,该方法返回后,集合将为空
  67. void clear();
  68.  
  69. // Comparison and hashing
  70. // 比较和散列
  71.  
  72. // 将指定的对象与集合进行比较
  73. boolean equals(Object o);
  74.  
  75. // 返回在这个集合的hashCode值
  76. int hashCode();
  77.  
  78. // 在此集合中的元素上创建Spliterator/
  79. // jdk 1.8 的新特性
  80. @Override
  81. default Spliterator<E> spliterator() {
  82. return Spliterators.spliterator(this, 0);
  83. }
  84.  
  85. // 返回以此集合为源的顺序Stream。/
  86. // jdk 1.8 的新特性
  87. default Stream<E> stream() {
  88. return StreamSupport.stream(spliterator(), false);
  89. }
  90.  
  91. // 以此集合作为源返回可能并行的Stream。 此方法允许返回顺序流。/
  92. // jdk1.8 新特性
  93. default Stream<E> parallelStream() {
  94. return StreamSupport.stream(spliterator(), true);
  95. }
  96. }

上面的源码中第17行的 iterator () 返回了一个迭代器对象 Iterator,可以使用这个迭代器一次访问集合中的元素。 Iterator 是一个接口,看看它在源码中的定义:

  1. public interface Iterator<E> {
  2.  
  3. // 如果这个迭代器对象还有元素的话就返回true
  4. boolean hasNext();
  5.  
  6. // 返回这个迭代器中的下一个元素
  7. E next();
  8.  
  9. // 从底层集合中移除此迭代器返回的最后一个元素。 每次调用next时,只能调用一次此方法。
  10. default void remove() {
  11. throw new UnsupportedOperationException("remove");
  12. }
  13.  
  14. // 对集合中剩余的每个元素执行给定的操作,知道处理完所有元素或者引发异常
  15. // jdk 1.8 新特性
  16. default void forEachRemaining(Consumer<? super E> action) {
  17. Objects.requireNonNull(action);
  18. while (hasNext())
  19. action.accept(next());
  20. }
  21. }

看完了这个迭代器,我们应该对集合元素的遍历方法有所思考,我们可以反复的调用hasNext,next 方法逐个的访问集合元素,我们还可以使用“for each” 带迭代器的循环访问任何实现了Iterable接口的对象,Iterable接口中定义的方法 都是为了迭代元素而存在的

  1. public interface Iterable<T> {
  2.  
  3. Iterator<T> iterator();
  4.  
  5. // 1.8 新特性
  6. default void forEach(Consumer<? super T> action) {
  7. Objects.requireNonNull(action);
  8. for (T t : this) {
  9. action.accept(t);
  10. }
  11. }
  12.  
  13. // 1.8 新特性
  14. default Spliterator<T> spliterator() {
  15. return Spliterators.spliteratorUnknownSize(iterator(), 0);
  16. }
  17. }

  而Collection接口扩展了 Iterable 接口,因此凡是 Collection 接口的实现,我们都可以使用“for each” 循环来遍历所有的元素。在JDK 1.8 中,我们甚至可以调用 forEachRemaining 方法并提供一个Lambda 表达式定义处理剩余元素的逻辑,知道结束。这3中迭代集合元素的方法我们会根据实际需求来选择。还有一个很重的问题就是元素被访问的顺序,它取决于集合的实现类型,后面我们将会对每一种实现类型详细分析。另外当我们使用迭代器来删除集合中的元素时,必须使用next方法先返回要删除的元素,然remove该元素,也就是这两个方法必须一前一后,否则将会抛出 IllegalStateException 异常。

  Collection接口中声明了很多对于集合来说很有用的方法,那么每一个Collection接口的实现类都应该具有这些通用的功能,但是每一种实现类都要重复这些逻辑,岂不烦人?于是在Collection接口的具体实现类之上提供了一个Collection的抽象实现 AbstractCollection,在该抽象类中,它将size,iterator 方法抽象化了,由具体集合实现类去完成。但是实现了集合的相关通用方法,当然,如果子类有更高效的实现的话,是可以覆盖的。

  在AbstractCollection抽象类中实现的通用方法主要有:

    • public boolean contains(Object o)
  1. public boolean contains(Object o) {
  2. // 得到一个迭代器对象,用于遍历集合的元素
  3. Iterator<E> it = iterator();
  4. // 如果需要判断的对象是 null 值
  5. if (o==null) {
  6. while (it.hasNext())
  7. if (it.next()==null) // 集合包含null 返回true
  8. return true;
  9. } else { // 判断的对象不为null
  10. while (it.hasNext()) // 循环遍历结合查找匹配
  11. if (o.equals(it.next())) // 使用传入对象的equals方法判断
  12. return true;
  13. }
  14. return false; // 没有找到,,返回false
  15. }
    •     public Object[] toArray() 
  1. public Object[] toArray() {
  2. // Estimate size of array; be prepared to see more or fewer elements
  3. // 创建一个和集合元素个数相同的对象数组,用于存储元素数据
  4. Object[] r = new Object[size()];
  5. // 返回迭代器
  6. Iterator<E> it = iterator();
  7. // 循环将集合元素放入对象数组中
  8. for (int i = 0; i < r.length; i++) {
  9. if (! it.hasNext()) // fewer elements than expected 元素少于预期的个数
  10. return Arrays.copyOf(r, i); // 将包含所有的元素的对象数组返回
  11. r[i] = it.next();
  12. }
  13. // 当迭代器返回的元素多于预期时,重新分配在toArray中使用的数组,并完成从迭代器填充它。否则返回该数组
  14. return it.hasNext() ? finishToArray(r, it) : r;
  15. }
    • public boolean remove(Object o)
  1. // 调用 Iterator 迭代器的方法执行删除操作
  2. public boolean remove(Object o) {
  3. // 得到一个迭代器对象,用于遍历集合的元素
  4. Iterator<E> it = iterator();
  5. //如果要删除的元素是 null
  6. if (o==null) {
  7. while (it.hasNext()) {
  8. if (it.next()==null) {
  9. it.remove();
  10. return true;
  11. }
  12. }
  13. } else {
  14. while (it.hasNext()) { // 使用传入对象的equals方法判断,找到并删除
  15. if (o.equals(it.next())) {
  16. it.remove();
  17. return true;
  18. }
  19. }
  20. }
  21. return false;
  22. }

以上就是 AbstractCollection主要实现的通用方法,其他的一些方法都是调用这些基本方法实现,或者是等具体的实现类实现的,点击查看更多方法。另外在该抽象类中还定义了如果使用数组实现的数组大小上限:

  1. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

实现了Collection的接口

  其中List是一个有序集合。元素会增加到容器中的特定位置。可以采用两种方式访问元素,使用迭代器访问,或者使用一个随机索引来访问,后一种方法为随机访问,这样可以按照任意顺序访问元素,而迭代器则必须顺序的访问元素。下面列出List与之父接口Collection不同的一些方法源码:

  1. public interface List<E> extends Collection<E> {
  2.  
  3. // 将该列表的每个元素替换为 将运算符应用于该元素的结果
  4. // jdk 1.8 特性
  5. default void replaceAll(UnaryOperator<E> operator) {
  6. Objects.requireNonNull(operator);
  7. final ListIterator<E> li = this.listIterator();
  8. while (li.hasNext()) {
  9. li.set(operator.apply(li.next()));
  10. }
  11. }
  12.  
  13. // 根据传入的规则将列表排序
  14. // jdkk 1.8 特性
  15. default void sort(Comparator<? super E> c) {
  16. Object[] a = this.toArray();
  17. Arrays.sort(a, (Comparator) c);
  18. ListIterator<E> i = this.listIterator();
  19. for (Object e : a) {
  20. i.next();
  21. i.set((E) e);
  22. }
  23. }
  24.  
  25. // 返回true的条件是 两个list的元素个数和顺序都相等
  26. boolean equals(Object o);
  27.  
  28. /**
  29. * 计算法则:
  30. * int hashCode = 1;
  31. * for (E e : list)
  32. * hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
  33. */
  34. int hashCode();
  35.  
  36. E get(int index);
  37.  
  38. E set(int index, E element);
  39.  
  40. int indexOf(Object o);
  41.  
  42. int lastIndexOf(Object o);
  43.  
  44. // 返回此列表中元素的列表迭代器
  45. ListIterator<E> listIterator();
  46.  
  47. // 返回指定索引的视图,也就是该列表的子列表,子列表和源列表的操作是可见的
  48. List<E> subList(int fromIndex, int toIndex);
  49.  
  50. }

List与Collection不同的方法定义

  Set接口等同于Collection(虽然也是继承自Collection接口),其方法的定义都与Collection差不多,但是Set接口方法的行为有更加严谨的要求,Set接口的add方法中不允许有重复的元素。Set方法中equals方法的定义:只要两个Set中含有相同的元素就为true,而不考虑元素的顺序。hashCode方法的定义:保证两个包含相同元素的 Set返回同样的散列码。因为Set中hashCode的计算是所有元素的hashCode之和。在此就不列出Set接口的代码了,具体我们在看具体实现的时候再说。

  SortedSet接口:队列与双端队列的定义,我们可以在方便的在尾部添加元素,头部删除元素,  这样有两个端头的队列,叫做双端队列,但是不能在队列的中间位置插入一个元素。在javase中队列的实现有ArrayDQueue和LinkedList。将在后面介绍。

  1. public interface SortedSet<E> extends Set<E> {
  2.  
  3. Comparator<? super E> comparator();
  4.  
  5. SortedSet<E> subSet(E fromElement, E toElement);
  6.  
  7. SortedSet<E> headSet(E toElement);
  8.  
  9. SortedSet<E> tailSet(E fromElement);
  10.  
  11. E first();
  12.  
  13. E last();
  14.  
  15. @Override
  16. default Spliterator<E> spliterator() {
  17. return new Spliterators.IteratorSpliterator<E>(
  18. this, Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED) {
  19. @Override
  20. public Comparator<? super E> getComparator() {
  21. return SortedSet.this.comparator();
  22. }
  23. };
  24. }
  25. }

Queue与Deque接口:

Collection的具体实现

ArrayList:底层基于数组实现,添加元素时判断数组容量,可以动态扩容,相应的功能实现看代码

定义:

  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
  3.  
  4. ....
  5.  
  6. }

构造函数及其相关属性:

  1. // 底层基于数组实现,定义用于存放元素的 对象数组
  2. transient Object[] elementData;
  3.  
  4. // 默认的容量大小
  5. private static final int DEFAULT_CAPACITY = 10;
  6.  
  7. // 创建指定大小的ArrayList时(指定为0)用于初始化一个指定容量的空的对象数组
  8. private static final Object[] EMPTY_ELEMENTDATA = {};
  9.  
  10. // 创建ArrayList时不指定初始化容量 创建的默认 为空的对象数组
  11. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  12.  
  13. // 创建指定大小的ArrayList
  14. public ArrayList(int initialCapacity) {
  15. if (initialCapacity > 0) {
  16. this.elementData = new Object[initialCapacity];
  17. } else if (initialCapacity == 0) { // 指定容量等于0 时,创建空的对象数组
  18. this.elementData = EMPTY_ELEMENTDATA;
  19. } else { // 参数不合法
  20. throw new IllegalArgumentException("Illegal Capacity: "+
  21. initialCapacity);
  22. }
  23. }
  24.  
  25. // 创建默认的对象数组
  26. public ArrayList() {
  27. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  28. }
  29.  
  30. // 根据传入的集合对象创建ArrayList
  31. public ArrayList(Collection<? extends E> c) {
  32. elementData = c.toArray();
  33. if ((size = elementData.length) != 0) {
  34. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  35. if (elementData.getClass() != Object[].class)
  36. elementData = Arrays.copyOf(elementData, size, Object[].class); // 复制数据到对象数组中
  37. } else {
  38. // replace with empty array.
  39. this.elementData = EMPTY_ELEMENTDATA; // 传入集合为空时
  40. }
  41. }

添加一个元素及其扩容策略:

  1. public boolean add(E e) {
  2. // 1. 保证容量的合理范围
  3. ensureCapacityInternal(size + 1); // Increments modCount!!
  4. elementData[size++] = e;
  5. return true;
  6. }
  7.  
  8. private void ensureCapacityInternal(int minCapacity) {
  9. // 2. 如果当前对象数组的大小小于 默认容量10 ,那么将容量增加到10
  10. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
  11. }
  12.  
  13. // 根据当前容量判断是否需要扩容
  14. private void ensureExplicitCapacity(int minCapacity) {
  15. modCount++;
  16.  
  17. // overflow-conscious code
  18. // 如果 当前容量小于对象数组的长度,扩容
  19. if (minCapacity - elementData.length > 0)
  20. grow(minCapacity); // 扩容方法
  21. }
  22.  
  23. // 计算当前容量是否小于最小要求10
  24. private static int calculateCapacity(Object[] elementData, int minCapacity) {
  25. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  26. return Math.max(DEFAULT_CAPACITY, minCapacity);
  27. }
  28. return minCapacity;
  29. }
  30.  
  31. // 扩容策略
  32. private void grow(int minCapacity) {
  33. // overflow-conscious code
  34. int oldCapacity = elementData.length; // 当前对象数组的长度
  35. int newCapacity = oldCapacity + (oldCapacity >> 1); // 新的容量等于 当前数组的长度 + 当前数组长度 / 2 ;也就是1.5倍
  36. if (newCapacity - minCapacity < 0) // 扩容容量是否满足最低要求
  37. newCapacity = minCapacity;
  38. if (newCapacity - MAX_ARRAY_SIZE > 0) // 新容量超过允许的数组最大值
  39. newCapacity = hugeCapacity(minCapacity); // 再加大数组的允许范围
  40. // minCapacity is usually close to size, so this is a win:
  41. elementData = Arrays.copyOf(elementData, newCapacity);
  42. }
  43.  
  44. private static int hugeCapacity(int minCapacity) {
  45. if (minCapacity < 0) // overflow
  46. throw new OutOfMemoryError();
  47. return (minCapacity > MAX_ARRAY_SIZE) ? // Integer 的最大值
  48. Integer.MAX_VALUE :
  49. MAX_ARRAY_SIZE;
  50. }

删除一个元素

  1. public E remove(int index) {
  2. // 下标的范围检查
  3. rangeCheck(index);
  4.  
  5. modCount++;
  6. E oldValue = elementData(index); // 即将删除的元素的值,临时保存,为返回用
  7.  
  8. int numMoved = size - index - 1; // 删除该元素,其他元素移动的次数
  9. if (numMoved > 0) // 移动次数大于0 ,合法
  10. System.arraycopy(elementData, index+1, elementData, index, // 通过拷贝的方式删除一个元素
  11. numMoved);
  12. elementData[--size] = null; // clear to let GC do its work
  13.  
  14. return oldValue; // 返回删除的元素
  15. }
  16.  
  17. private void rangeCheck(int index) {
  18. if (index >= size)
  19. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  20. }

用于元素操作的内部类

  1. // 这三个内部类通过定义就可以看到,它们都是继承了相应的接口
  2. // 针对基于数组实现的ArrayList 方便相应的操作,在这就不一一解释了,都是见名知意的,
  3. private class Itr implements Iterator<E> {
  4.  
  5. }
  6.  
  7. private class ListItr extends Itr implements ListIterator<E> {
  8.  
  9. }
  10.  
  11. private class SubList extends AbstractList<E> implements RandomAccess {
  12.  
  13. }

LinkedList:底层基于链表实现。

定义:

  1. public class LinkedList<E>
  2. extends AbstractSequentialList<E>
  3. implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
  4.  
  5. ...
  6.  
  7. }

构造函数及其相关属性:LinkedList基于链表实现,在其内部定义了一个Node类用户存放数据和维持节点之间的关系。

  1. // 记录元素的个数
  2. transient int size = 0;
  3.  
  4. // 链表的第一个节点
  5. transient Node<E> first;
  6.  
  7. // 最后一个节点
  8. transient Node<E> last;
  9.  
  10. // 构造哦一个空的链表
  11. public LinkedList() {
  12.  
  13. }
  14.  
  15. // 根据传入的集合类构建一个链表
  16. // 具体的addAll 在添加元素的时候分析
  17. public LinkedList(Collection<? extends E> c) {
  18. this();
  19. addAll(c);
  20. }
  21.  
  22. // 构造链表的几点,是LinkedList的静态内部类
  23. private static class Node<E> {
  24. E item; // 真实数据
  25. Node<E> next; // 下一个节点
  26. Node<E> prev; // 前一个节点
  27.  
  28. // 节点的构造函数
  29. Node(Node<E> prev, E element, Node<E> next) {
  30. this.item = element;
  31. this.next = next;
  32. this.prev = prev;
  33. }
  34. }

添加一个元素:包括在头,尾,中间任意节点插入元素

  1. // 在链表的头结点添加一个元素
  2. public void addFirst(E e) {
  3. linkFirst(e);
  4. }
  5.  
  6. private void linkFirst(E e) {
  7. final Node<E> f = first;
  8. final Node<E> newNode = new Node<>(null, e, f); // 根据传入的数据新创建一个节点,将头节点作为下一节点
  9. first = newNode; //更新头结点为新创建的节点
  10. if (f == null) // 如果头结点为空,也就是空链表的时候
  11. last = newNode; // 头等于尾
  12. else
  13. f.prev = newNode; // 原来的头结点的上一节点为新创建的节点
  14. size++;
  15. modCount++;
  16. }
  17.  
  18. // 在链表的末尾添加一个元素
  19. public void addLast(E e) {
  20. linkLast(e);
  21. }
  22.  
  23. void linkLast(E e) {
  24. final Node<E> l = last;
  25. final Node<E> newNode = new Node<>(l, e, null); // 根据传入的数据新创建一个节点,将原始尾节点作为前一节点
  26. last = newNode; // 更新尾节点
  27. if (l == null) // 为空链表时
  28. first = newNode; // 头等于尾
  29. else
  30. l.next = newNode; // 原始尾节点的下一个等于新创建的节点
  31. size++;
  32. modCount++;
  33. }
  34.  
  35. // 在任意位置插入元素
  36. public void add(int index, E element) {
  37. checkPositionIndex(index); // 索引的范围检查
  38.  
  39. if (index == size) // 如果 索引是最后个 直接加入
  40. linkLast(element);
  41. else // 否则
  42. linkBefore(element, node(index)); // 在给定索引的元素前面插入该元素
  43. }
  44.  
  45. void linkBefore(E e, Node<E> succ) {
  46. // assert succ != null;
  47. final Node<E> pred = succ.prev; // 给定索引的前一节点
  48. final Node<E> newNode = new Node<>(pred, e, succ); // 创建一个以给定索引的前一节点,以及给定索引为下一节点的新节点
  49. succ.prev = newNode; // 给定索引的节点为新建节点
  50. if (pred == null) // 给定索引的前一节点为空的情况
  51. first = newNode;
  52. else // 否则 给定索引的前一节点的下一节点为新建的节点
  53. pred.next = newNode;
  54. size++;
  55. modCount++;
  56. }

删除一个元素:包括在头,尾,中间任意节点插入元素

  1. public E removeFirst() {
  2. final Node<E> f = first;
  3. if (f == null) // 没有元素时 ,抛出异常
  4. throw new NoSuchElementException();
  5. return unlinkFirst(f);
  6. }
  7.  
  8. public E removeLast() {
  9. final Node<E> l = last;
  10. if (l == null) // 没有元素时 ,抛出异常
  11. throw new NoSuchElementException();
  12. return unlinkLast(l);
  13. }
  14.  
  15. private E unlinkFirst(Node<E> f) {
  16. // assert f == first && f != null;
  17. final E element = f.item; // 保存即将删除元素的数据 返回用
  18. final Node<E> next = f.next; // 即将删除元素的下一个
  19. f.item = null; // 删除元素
  20. f.next = null; // help GC
  21. first = next; // 更新头加点
  22. if (next == null) // 为空时
  23. last = null;
  24. else
  25. next.prev = null;
  26. size--;
  27. modCount++;
  28. return element;
  29. }
  30.  
  31. private E unlinkLast(Node<E> l) {
  32. // assert l == last && l != null;
  33. final E element = l.item;
  34. final Node<E> prev = l.prev;
  35. l.item = null;
  36. l.prev = null; // help GC
  37. last = prev;
  38. if (prev == null)
  39. first = null;
  40. else
  41. prev.next = null;
  42. size--;
  43. modCount++;
  44. return element;
  45. }

根据索引查找元素:此方法LinkedList做了优化,看代码

  1. // 获取指定索引的元素
  2. public E get(int index) {
  3. checkElementIndex(index);
  4. return node(index).item;
  5. }
  6.  
  7. // 优化
  8. Node<E> node(int index) {
  9. // assert isElementIndex(index);
  10.  
  11. if (index < (size >> 1)) { // 查找的索引小于 总个数的 1/2
  12. Node<E> x = first;
  13. for (int i = 0; i < index; i++) // 遍历到索引的位置
  14. x = x.next;
  15. return x;
  16. } else { // 查找的索引大于 总个数的 1/2
  17. Node<E> x = last;
  18. for (int i = size - 1; i > index; i--) // 从尾到头遍历查找元素
  19. x = x.prev;
  20. return x;
  21. }
  22. }

在LinkedList的实现中我们可以看到,它利用元素的插入和删除,但是对于索引访问元素的操作,需要从头开始遍历,虽然做了微小的优化,但是还是不如数组实现的访问速度。

Vector:当我们在需要使用动态数组时,还有一个Vector可以满足我们的要求,它也是基于数组实现的有序集合,但是它与ArrayList的最大区别是Vector的所有方法都实现了同步,可以由两个线程安全的访问Vector对象,但是由一个线程访问Vector时,代码要在同步操作上耗费大量的时间。因为此性能较低,我们也不常用,在此不做讨论。

HashSet: 基于散列表的Set,Set中没有重复的元素,元素是否重复是基于散列码比较的,将元素散列在表的各个位置上,所以访问元素的顺序是随机的。适合不关心集合中元素的顺序时使用。

散列表:在java中使用的是链表数组实现的,每个列表叫做bucket,元素根据对象的散列码与bucket总数取余,决定元素的存储位置。如果bucket容量满时,将会出现hash冲突,性能下降,因此对于bucket总数的设置有学问,一般设置为预计插入元素个数的75%~150%,最好设置为素数,以防hash聚集。当我们设置的bucket总数小于预计插入元素时,此时会发生在散列,再散列就是创建一个数量更大的新的bucket,并将原bucket的数据复制过来,再弃用原bucket。何时进行在散列的判断,称为负载因子。java实现中默认为0.75.散列码(hashCode)是根据对象的内存地址转换而来的整数.

定义:

  1. public class HashSet<E>
  2. extends AbstractSet<E>
  3. implements Set<E>, Cloneable, java.io.Serializable {
  4.  
  5. ...
  6. }

构造方法与属性定义:

  1. // 底层基于HashMap实现
  2. private transient HashMap<E,Object> map;
  3.  
  4. private static final Object PRESENT = new Object();
  5.  
  6. public HashSet() {
  7. map = new HashMap<>();
  8. }
  9.  
  10. // 根据传入的集合类,创建HashMap,如果元素的个数少于默认值,那么创建时指定为默认值,
  11. public HashSet(Collection<? extends E> c) {
  12. map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
  13. addAll(c);
  14. }
  15.  
  16. // 创建时指定容量和负载因子
  17. public HashSet(int initialCapacity, float loadFactor) {
  18. map = new HashMap<>(initialCapacity, loadFactor);
  19. }
  20.  
  21. // 指定容量
  22. public HashSet(int initialCapacity) {
  23. map = new HashMap<>(initialCapacity);
  24. }
  25.  
  26. // 为包调用的构造函数,仅为实现类LinkedHashSet使用
  27. HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  28. map = new LinkedHashMap<>(initialCapacity, loadFactor);
  29. }

HashSet中对元素的操作都是基于HashMap实现的,因此具体实现将在HashMap中详细介绍。

TreeSet:与HashSet类似,但是它是有序的Set,可以以任意顺序将数据插入到集合中,当我们遍历这个集合时,元素总是以排好的顺序输出。如名所示,TreeSet的排序使用树完成的(当前使用的是红黑树),根据特性可知,插入元素到TreeSet中比HashSet要慢,但是比数组实现的ArrayList和基于链表的LinkedList要快,TreeSet中元素比较是使用Comparable接口的comparator方法。实际应用中会根据实际需求是否需要对元素排序而在HashSet和TreeSet中选择。

定义:

  1. public class TreeSet<E> extends AbstractSet<E>
  2. implements NavigableSet<E>, Cloneable, java.io.Serializable {
  3.  
  4. ...
  5. }

在TreeSet的定义中可以看到,它使用了 NavigableSet 接口,在这个接口中增加了几个便于定位元素和反向变遍历的方法。

构造函数与相关属性:通过构造方法不难看出,TreeSet的实现都是调用TreeMap实现的,同样,在后面再详细介绍。

  1. private transient NavigableMap<E,Object> m;
  2.  
  3. TreeSet(NavigableMap<E,Object> m) {
  4. this.m = m;
  5. }
  6.  
  7. public TreeSet() {
  8. this(new TreeMap<E,Object>());
  9. }
  10.  
  11. public TreeSet(Comparator<? super E> comparator) {
  12. this(new TreeMap<>(comparator));
  13. }
  14.  
  15. public TreeSet(Collection<? extends E> c) {
  16. this();
  17. addAll(c);
  18. }
  19.  
  20. public TreeSet(SortedSet<E> s) {
  21. this(s.comparator());
  22. addAll(s);
  23. }

ArrayDeque:基于数组实现的双端队列

定义:

  1. public class ArrayDeque<E> extends AbstractCollection<E>
  2. implements Deque<E>, Cloneable, Serializable {
  3.  
  4. ...
  5. }

构造函数与属性

  1. // 用于存放元素的 对象数组
  2. transient Object[] elements;
  3.  
  4. // 队头的下标
  5. transient int head;
  6.  
  7. // 队尾的下标
  8. transient int tail;
  9.  
  10. // 队列默认的容量
  11. private static final int MIN_INITIAL_CAPACITY = 8;
  12.  
  13. public ArrayDeque() {
  14. elements = new Object[16];
  15. }
  16.  
  17. public ArrayDeque(int numElements) {
  18. allocateElements(numElements);
  19. }
  20.  
  21. public ArrayDeque(Collection<? extends E> c) {
  22. allocateElements(c.size());
  23. addAll(c);
  24. }

PriorityQueue:优先级队列。利用基于数组实现的堆的数据结构,元素的顺序和插入的顺序无关,而是和本身的优先级相关。与TreeSet类似,元素优先级的判断是根据实现了Comparable接口的comparator()方法判断的。对于元素的插入,利用二叉树的自调整 ,总是将自小的元素移动到根。而在元素删除的时候,总是删除数组最后的元素,也是数组优先级最大的元素。

Map接口

Map用来存放 key/value 对,可以可以根据提供的key,找到相应的value。其接口的定义如下 ():

  1. public interface Map<K,V> {
  2.  
  3. // 元素个数
  4. int size();
  5.  
  6. // 是否为空
  7. boolean isEmpty();
  8.  
  9. // 是否包含指定的key
  10. boolean containsKey(Object key);
  11.  
  12. // 是否包含指定的value
  13. boolean containsValue(Object value);
  14.  
  15. // 根据key 返回value
  16. V get(Object key);
  17.  
  18. // 加入一个键值对
  19. V put(K key, V value);
  20.  
  21. // 根据key,删除value
  22. V remove(Object key);
  23.  
  24. void putAll(Map<? extends K, ? extends V> m);
  25.  
  26. // 清空map中的所有元素
  27. void clear();
  28.  
  29. // 将map中的所有值包含在一个Set中返回,在此处该该Set的定义是视图,但是由Map支持,因此在Map中的修改和Set中的修改将是同步的,
  30. Set<K> keySet();
  31.  
  32. // 同样的,返回map中所有的值,但是此时是放在集合对象中,同样修改也是相互影响的。多说一句,为什么键和值的返回类型不一样?
  33. // 这个和Map的实现有关,在map中,键的存放和Set一样,也是基于hashCode的,而值的存储可以放在Collection中,可以基于数组实现。
  34. Collection<V> values();
  35.  
  36. // 将Map中的元素包装为视图在Set中返回,其泛型是Entry,是Map的内部接口,其中定义了对Map的键值的相关操作方法,接口定义如下
  37. Set<Map.Entry<K, V>> entrySet();
  38.  
  39. // 操作Map中键值的接口定义
  40. interface Entry<K,V> {
  41.  
  42. // 获取键
  43. K getKey();
  44.  
  45. // 获取值
  46. V getValue();
  47.  
  48. // 更新值操作
  49. V setValue(V value);
  50.  
  51. // 判断对象相等
  52. boolean equals(Object o);
  53.  
  54. // 散列码
  55. int hashCode();
  56.  
  57. // 一下方法为jdk8 中的新特性
  58.  
  59. public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
  60. return (Comparator<Map.Entry<K, V>> & Serializable)
  61. (c1, c2) -> c1.getKey().compareTo(c2.getKey());
  62. }
  63.  
  64. public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
  65. return (Comparator<Map.Entry<K, V>> & Serializable)
  66. (c1, c2) -> c1.getValue().compareTo(c2.getValue());
  67. }
  68.  
  69. public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
  70. Objects.requireNonNull(cmp);
  71. return (Comparator<Map.Entry<K, V>> & Serializable)
  72. (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
  73. }
  74.  
  75. public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
  76. Objects.requireNonNull(cmp);
  77. return (Comparator<Map.Entry<K, V>> & Serializable)
  78. (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
  79. }
  80. }
  81.  
  82. boolean equals(Object o);
  83.  
  84. int hashCode();
  85.  
  86. // 一下为JDK8 中的新特性
  87.  
  88. default V getOrDefault(Object key, V defaultValue) {
  89. V v;
  90. return (((v = get(key)) != null) || containsKey(key))
  91. ? v
  92. : defaultValue;
  93. }
  94.  
  95. default void forEach(BiConsumer<? super K, ? super V> action) {
  96. Objects.requireNonNull(action);
  97. for (Map.Entry<K, V> entry : entrySet()) {
  98. K k;
  99. V v;
  100. try {
  101. k = entry.getKey();
  102. v = entry.getValue();
  103. } catch(IllegalStateException ise) {
  104. // this usually means the entry is no longer in the map.
  105. throw new ConcurrentModificationException(ise);
  106. }
  107. action.accept(k, v);
  108. }
  109. }
  110.  
  111. default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
  112. Objects.requireNonNull(function);
  113. for (Map.Entry<K, V> entry : entrySet()) {
  114. K k;
  115. V v;
  116. try {
  117. k = entry.getKey();
  118. v = entry.getValue();
  119. } catch(IllegalStateException ise) {
  120. // this usually means the entry is no longer in the map.
  121. throw new ConcurrentModificationException(ise);
  122. }
  123.  
  124. // ise thrown from function is not a cme.
  125. v = function.apply(k, v);
  126.  
  127. try {
  128. entry.setValue(v);
  129. } catch(IllegalStateException ise) {
  130. // this usually means the entry is no longer in the map.
  131. throw new ConcurrentModificationException(ise);
  132. }
  133. }
  134. }
  135.  
  136. default V putIfAbsent(K key, V value) {
  137. V v = get(key);
  138. if (v == null) {
  139. v = put(key, value);
  140. }
  141.  
  142. return v;
  143. }
  144.  
  145. default boolean remove(Object key, Object value) {
  146. Object curValue = get(key);
  147. if (!Objects.equals(curValue, value) ||
  148. (curValue == null && !containsKey(key))) {
  149. return false;
  150. }
  151. remove(key);
  152. return true;
  153. }
  154.  
  155. default boolean replace(K key, V oldValue, V newValue) {
  156. Object curValue = get(key);
  157. if (!Objects.equals(curValue, oldValue) ||
  158. (curValue == null && !containsKey(key))) {
  159. return false;
  160. }
  161. put(key, newValue);
  162. return true;
  163. }
  164.  
  165. default V replace(K key, V value) {
  166. V curValue;
  167. if (((curValue = get(key)) != null) || containsKey(key)) {
  168. curValue = put(key, value);
  169. }
  170. return curValue;
  171. }
  172.  
  173. default V computeIfAbsent(K key,
  174. Function<? super K, ? extends V> mappingFunction) {
  175. Objects.requireNonNull(mappingFunction);
  176. V v;
  177. if ((v = get(key)) == null) {
  178. V newValue;
  179. if ((newValue = mappingFunction.apply(key)) != null) {
  180. put(key, newValue);
  181. return newValue;
  182. }
  183. }
  184.  
  185. return v;
  186. }
  187.  
  188. default V computeIfPresent(K key,
  189. BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  190. Objects.requireNonNull(remappingFunction);
  191. V oldValue;
  192. if ((oldValue = get(key)) != null) {
  193. V newValue = remappingFunction.apply(key, oldValue);
  194. if (newValue != null) {
  195. put(key, newValue);
  196. return newValue;
  197. } else {
  198. remove(key);
  199. return null;
  200. }
  201. } else {
  202. return null;
  203. }
  204. }
  205.  
  206. default V compute(K key,
  207. BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  208. Objects.requireNonNull(remappingFunction);
  209. V oldValue = get(key);
  210.  
  211. V newValue = remappingFunction.apply(key, oldValue);
  212. if (newValue == null) {
  213. // delete mapping
  214. if (oldValue != null || containsKey(key)) {
  215. // something to remove
  216. remove(key);
  217. return null;
  218. } else {
  219. // nothing to do. Leave things as they were.
  220. return null;
  221. }
  222. } else {
  223. // add or replace old mapping
  224. put(key, newValue);
  225. return newValue;
  226. }
  227. }
  228.  
  229. default V merge(K key, V value,
  230. BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
  231. Objects.requireNonNull(remappingFunction);
  232. Objects.requireNonNull(value);
  233. V oldValue = get(key);
  234. V newValue = (oldValue == null) ? value :
  235. remappingFunction.apply(oldValue, value);
  236. if(newValue == null) {
  237. remove(key);
  238. } else {
  239. put(key, newValue);
  240. }
  241. return newValue;
  242. }
  243.  
  244. }

Map具体的实现类:

HashMap: 采用数组+链表+红黑树实现,当链表的长度超过8 时,转而使用红黑树。

定义:

  1. public class HashMap<K,V> extends AbstractMap<K,V>
  2. implements Map<K,V>, Cloneable, Serializable {
  3.  
  4. ...
  5. }

构造函数及其属性:

  1. // 允许的最大容量
  2. static final int MAXIMUM_CAPACITY = 1 << 30;
  3.  
  4. // 默认的容量大小
  5. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  6.  
  7. // 将链表转为红黑树的阈值,当链表的个数大于8 时,转为红黑树
  8. static final int TREEIFY_THRESHOLD = 8;
  9.  
  10. // 红黑树转为链表
  11. static final int UNTREEIFY_THRESHOLD = 6;
  12.  
  13. // 红黑树的默认容量大小
  14. static final int MIN_TREEIFY_CAPACITY = 64;
  15.  
  16. // 负载因子,真实的元素个数占总容量的比例,超过后就会扩容
  17. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  18.  
  19. // 传入容量大小和负载因子创建hashMap
  20. public HashMap(int initialCapacity, float loadFactor) {
  21. if (initialCapacity < 0)// 容量小于0
  22. throw new IllegalArgumentException("Illegal initial capacity: " +
  23. initialCapacity);
  24. if (initialCapacity > MAXIMUM_CAPACITY) // 超出最大容量 那么容量就是 2^30
  25. initialCapacity = MAXIMUM_CAPACITY;
  26. if (loadFactor <= 0 || Float.isNaN(loadFactor)) // 负载因子的合法性
  27. throw new IllegalArgumentException("Illegal load factor: " +
  28. loadFactor);
  29. this.loadFactor = loadFactor;
  30. this.threshold = tableSizeFor(initialCapacity);
  31. }
  32.  
  33. public HashMap(int initialCapacity) {
  34. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  35. }
  36.  
  37. public HashMap() {
  38. this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
  39. }
  40.  
  41. public HashMap(Map<? extends K, ? extends V> m) {
  42. this.loadFactor = DEFAULT_LOAD_FACTOR;
  43. putMapEntries(m, false);
  44. }

数据的封装:当我们将一个键值对放入hashmap的时候,键值对实际上被封装为一个Node,该Node实现了Map接口中的Entry,源码如下:

  1. static class Node<K,V> implements Map.Entry<K,V> {
  2. final int hash; // 这个node对象的hash值
  3. final K key; // 键
  4. V value; // 值
  5. Node<K,V> next; // 链表中的下一个
  6.  
  7. // 构造函数
  8. Node(int hash, K key, V value, Node<K,V> next) {
  9. this.hash = hash;
  10. this.key = key;
  11. this.value = value;
  12. this.next = next;
  13. }
  14.  
  15. public final K getKey() { return key; }
  16. public final V getValue() { return value; }
  17. public final String toString() { return key + "=" + value; }
  18.  
  19. // hashCode的计算方法 ^异或运算:两个数转为二进制,然后从高位开始比较,如果相同则为0,不相同则为1。
  20. public final int hashCode() {
  21. return Objects.hashCode(key) ^ Objects.hashCode(value); // 键 ^值
  22. }
  23.  
  24. // 更新Node对象的值
  25. public final V setValue(V newValue) {
  26. V oldValue = value;
  27. value = newValue;
  28. return oldValue;
  29. }
  30.  
  31. // 判断存入的对象是否相等的方法 ,地址相同或者键值都相同返回true
  32. public final boolean equals(Object o) {
  33. if (o == this) // 比较地址
  34. return true;
  35. if (o instanceof Map.Entry) { // 比较键和值的equals方法
  36. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  37. if (Objects.equals(key, e.getKey()) &&
  38. Objects.equals(value, e.getValue()))
  39. return true;
  40. }
  41. return false;
  42. }
  43. }

数据的存放对象:

  1. // 存放数据的是Node类型的数组
  2. transient Node<K,V>[] table;
  3.  
  4. // hash表的负载因子
  5. final float loadFactor;
  6.  
  7. // 实际存放元素的个数,以此判断是否需要扩容 (threshold = capacity * loadFactor)
  8. int threshold;
  9.  
  10. // 修改次数
  11. transient int modCount;
  12.  
  13. // 键值对的数量
  14. transient int size;
  15.  
  16. // 保持缓存?
  17. transient Set<Map.Entry<K,V>> entrySet;

放入一个键值对的操作:第一插入元素时对数组扩容,分配空间

  1. // 放入一个键值映射,
  2. public V put(K key, V value) {
  3. return putVal(hash(key), key, value, false, true); // 如果键对应的值已经存在了,那么就替换旧值
  4. }
  5.  
  6. /**
  7. * Implements Map.put and related methods
  8. *
  9. * @param hash hash for key 键的hash值 ,计算方法在Node中定义,看上面的Node源码
  10. * @param key the key 键
  11. * @param value the value to put 值
  12. * @param onlyIfAbsent if true, don't change existing value 是否不改变已经存在的值
  13. * @param evict if false, the table is in creation mode. 表的模式? false处于创建模式
  14. * @return previous value, or null if none 返回该key对应的以前的值,如果没有,那么返回 null
  15. */
  16. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  17. boolean evict) {
  18. Node<K,V>[] tab; Node<K,V> p; int n, i; // tab为存放数据的数组, p 为根据 key 计算得到的数组下标对应的node,n为数组当前的长度,
  19. if ((tab = table) == null || (n = tab.length) == 0) // 如果存放对象的 数组为空,或者长度为0
  20. n = (tab = resize()).length; // 对数组进行第一次扩容, 这里说明hashmap 数组的初始化是在第一次放入元素时,而不是在创建的时候
  21. if ((p = tab[i = (n - 1) & hash]) == null) // 数组的长度 n - 1 和 键的hash值 与运算得到数组下标,如果该值为空,直接放入,位与运算 & :两个数都转为二进制,然后从高位开始比较,如果两个数都为1则为1,否则为0。
  22. tab[i] = newNode(hash, key, value, null);
  23. else { // 如果不为空,那么放入链表?
  24. Node<K,V> e; K k;
  25. if (p.hash == hash && // 放入的元素和已有的元素 key hash相等且 equals返回true
  26. ((k = p.key) == key || (key != null && key.equals(k))))
  27. e = p; // key相等时,e = 当前下标对应的元素。
  28. else if (p instanceof TreeNode) // 如果是红黑树的节点,按照红黑树的方法插入
  29. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  30. else { // hash冲突的解决办法
  31. for (int binCount = 0; ; ++binCount) {
  32. if ((e = p.next) == null) { // e = 下标对应的元素的下一节点为null
  33. p.next = newNode(hash, key, value, null); // 那么下一个就是等于新创建的节点 加入链表
  34. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st // 当链表的长度大于等于 TREEIFY_THRESHOLD = 8,转而使用红黑树,注意有一个 -1的操作,也就是7的时候就转了。
  35. treeifyBin(tab, hash); // 红黑树的操作
  36. break;
  37. }
  38. if (e.hash == hash && // 创建的 key与 传入的key 相同
  39. ((k = e.key) == key || (key != null && key.equals(k))))
  40. break;
  41. p = e; // 插入链表
  42. }
  43. }
  44. if (e != null) { // existing mapping for key
  45. V oldValue = e.value;
  46. if (!onlyIfAbsent || oldValue == null) // 根据参数判断是否替换
  47. e.value = value;
  48. afterNodeAccess(e); // 不替换,加入链表后面
  49. return oldValue;
  50. }
  51. }
  52. ++modCount;
  53. if (++size > threshold) // 判断是否需要扩容,
  54. resize();
  55. afterNodeInsertion(evict);
  56. return null;
  57. }

取出一个元素的操作:

  1. // 根据key取出元素
  2. public V get(Object key) {
  3. Node<K,V> e;
  4. return (e = getNode(hash(key), key)) == null ? null : e.value;
  5. }
  6.  
  7. final Node<K,V> getNode(int hash, Object key) {
  8. Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  9. if ((tab = table) != null && (n = tab.length) > 0 && // 检查数组有效性
  10. (first = tab[(n - 1) & hash]) != null) {
  11. if (first.hash == hash && // always check first node // 第一个就相等
  12. ((k = first.key) == key || (key != null && key.equals(k))))
  13. return first;
  14. if ((e = first.next) != null) {
  15. if (first instanceof TreeNode) // 是否为红黑树
  16. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  17. do { // 循环链表查找key对应的节点
  18. if (e.hash == hash &&
  19. ((k = e.key) == key || (key != null && key.equals(k))))
  20. return e;
  21. } while ((e = e.next) != null);
  22. }
  23. }
  24. return null;
  25. }

扩容机制:

  1. final Node<K,V>[] resize() {
  2. Node<K,V>[] oldTab = table; // 原来的数组
  3. int oldCap = (oldTab == null) ? 0 : oldTab.length; // 原数组的容量
  4. int oldThr = threshold; // 原来的扩容限制值
  5. int newCap, newThr = 0;
  6. if (oldCap > 0) { // 如果原来的容量大于0
  7. if (oldCap >= MAXIMUM_CAPACITY) { // 如果原来的容量大于等于最大容量限制 2^30
  8. threshold = Integer.MAX_VALUE; // 那么扩容限制设置为 最大值
  9. return oldTab; // 返回原来的数组
  10. }
  11. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  12. oldCap >= DEFAULT_INITIAL_CAPACITY) // 否则如果新容量为原来的两倍并且小于最大容量
  13. newThr = oldThr << 1; // double threshold // 新的扩容限制也设为原来的两倍
  14. }
  15. else if (oldThr > 0) // initial capacity was placed in threshold // 如果原来的扩容限制大于0
  16. newCap = oldThr; // 那么新的容量等于 原来的扩容限制
  17. else { // zero initial threshold signifies using defaults
  18. newCap = DEFAULT_INITIAL_CAPACITY; // 否则新的容量设置为默认 16
  19. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 新的扩容限制 newThr 等于 = 默认的加载因子 0.75f * 默认的容量 16
  20. }
  21. if (newThr == 0) { // 如果新扩容限制 = 0
  22. float ft = (float)newCap * loadFactor; // 计算得到
  23. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  24. (int)ft : Integer.MAX_VALUE);
  25. }
  26. threshold = newThr; // 设置新的扩容限制
  27. @SuppressWarnings({"rawtypes","unchecked"})
  28. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // 根据新的容量创建数组
  29. table = newTab;
  30. // 如果原来的数组不为空,那么需要将原来数组的数据复制到新数组
  31. if (oldTab != null) {
  32. for (int j = 0; j < oldCap; ++j) {
  33. Node<K,V> e;
  34. if ((e = oldTab[j]) != null) {
  35. oldTab[j] = null; // 置空,便于垃圾回收
  36. if (e.next == null) // 如果为链表是,判断当前下标如果不再有元素
  37. newTab[e.hash & (newCap - 1)] = e; // 放入的位置是该元素的hash 和 新的容量 - 1 与运算 的得到的下标
  38. else if (e instanceof TreeNode) // 如果为红黑树的时候 ,
  39. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); // 红黑树拆分
  40. else { // preserve order // 不为红黑树,但是当前数组的下标对应的链表中还有元素
  41. Node<K,V> loHead = null, loTail = null;
  42. Node<K,V> hiHead = null, hiTail = null;
  43. Node<K,V> next;
  44. // 循环复制链表中的元素到新数组
  45. do {
  46. next = e.next;
  47. if ((e.hash & oldCap) == 0) {
  48. if (loTail == null)
  49. loHead = e;
  50. else
  51. loTail.next = e;
  52. loTail = e;
  53. }
  54. else {
  55. if (hiTail == null)
  56. hiHead = e;
  57. else
  58. hiTail.next = e;
  59. hiTail = e;
  60. }
  61. } while ((e = next) != null);
  62. if (loTail != null) {
  63. loTail.next = null;
  64. newTab[j] = loHead;
  65. }
  66. if (hiTail != null) {
  67. hiTail.next = null;
  68. newTab[j + oldCap] = hiHead;
  69. }
  70. }
  71. }
  72. }
  73. }
  74. return newTab;
  75. }

遍历:HashMap有一个内部类EntrySet,其中定义了操作 map中数据的系列方法,我们的数据都是放在 Entry里面的。entrySet方法就是将Entry放在Set中返回了,我们再一次迭代该Set就完成了hashMap的遍历。

  1. public Set<Map.Entry<K,V>> entrySet() {
  2. Set<Map.Entry<K,V>> es;
  3. return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
  4. }
  5.  
  6. final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
  7. public final int size() { return size; }
  8. public final void clear() { HashMap.this.clear(); }
  9. public final Iterator<Map.Entry<K,V>> iterator() {
  10. return new EntryIterator();
  11. }
  12. public final boolean contains(Object o) {
  13. if (!(o instanceof Map.Entry))
  14. return false;
  15. Map.Entry<?,?> e = (Map.Entry<?,?>) o;
  16. Object key = e.getKey();
  17. Node<K,V> candidate = getNode(hash(key), key);
  18. return candidate != null && candidate.equals(e);
  19. }
  20. public final boolean remove(Object o) {
  21. if (o instanceof Map.Entry) {
  22. Map.Entry<?,?> e = (Map.Entry<?,?>) o;
  23. Object key = e.getKey();
  24. Object value = e.getValue();
  25. return removeNode(hash(key), key, value, true, true) != null;
  26. }
  27. return false;
  28. }
  29. public final Spliterator<Map.Entry<K,V>> spliterator() {
  30. return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
  31. }
  32. public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
  33. Node<K,V>[] tab;
  34. if (action == null)
  35. throw new NullPointerException();
  36. if (size > 0 && (tab = table) != null) {
  37. int mc = modCount;
  38. for (int i = 0; i < tab.length; ++i) {
  39. for (Node<K,V> e = tab[i]; e != null; e = e.next)
  40. action.accept(e);
  41. }
  42. if (modCount != mc)
  43. throw new ConcurrentModificationException();
  44. }
  45. }
  46. }
  47.  
  48. final class EntryIterator extends HashIterator
  49. implements Iterator<Map.Entry<K,V>> {
  50. public final Map.Entry<K,V> next() { return nextNode(); }
  51. }

WeakHashMap:

IdentityHashMap:

LinkedHashMap:

TreeMap:使用树构建的有序映射。排序的依据是Comparable接口。

SortedMap:

EnumMap:

HashTable:

最后附上一张整个集合框架的概览图:

[集合]Collection集合框架源码分析的更多相关文章

  1. List-LinkedList、set集合基础增强底层源码分析

    List-LinkedList 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 继上一章继续讲解,上章内容: List-ArreyLlist集合基础增强底层源码分析:https:// ...

  2. java集合系列之LinkedList源码分析

    java集合系列之LinkedList源码分析 LinkedList数据结构简介 LinkedList底层是通过双端双向链表实现的,其基本数据结构如下,每一个节点类为Node对象,每个Node节点包含 ...

  3. java集合系列之ArrayList源码分析

    java集合系列之ArrayList源码分析(基于jdk1.8) ArrayList简介 ArrayList时List接口的一个非常重要的实现子类,它的底层是通过动态数组实现的,因此它具备查询速度快, ...

  4. Java集合系列[4]----LinkedHashMap源码分析

    这篇文章我们开始分析LinkedHashMap的源码,LinkedHashMap继承了HashMap,也就是说LinkedHashMap是在HashMap的基础上扩展而来的,因此在看LinkedHas ...

  5. List-ArrayList集合基础增强底层源码分析

    List集合基础增强底层源码分析 作者:Stanley 罗昊 [转载请注明出处和署名,谢谢!] 集合分为三个系列,分别为:List.set.map List系列 特点:元素有序可重复 有序指的是元素的 ...

  6. YII框架源码分析(百度PHP大牛创作-原版-无广告无水印)

           YII 框架源码分析    百度联盟事业部——黄银锋 目 录 1. 引言 3 1.1.Yii 简介 3 1.2.本文内容与结构 3 2.组件化与模块化 4 2.1.框架加载和运行流程 4 ...

  7. 介绍开源的.net通信框架NetworkComms框架 源码分析

    原文网址: http://www.cnblogs.com/csdev Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 售价249英镑 我曾经花了 ...

  8. Android Small插件化框架源码分析

    Android Small插件化框架源码分析 目录 概述 Small如何使用 插件加载流程 待改进的地方 一.概述 Small是一个写得非常简洁的插件化框架,工程源码位置:https://github ...

  9. Spark RPC框架源码分析(一)简述

    Spark RPC系列: Spark RPC框架源码分析(一)运行时序 Spark RPC框架源码分析(二)运行时序 Spark RPC框架源码分析(三)运行时序 一. Spark rpc框架概述 S ...

  10. Spark RPC框架源码分析(二)RPC运行时序

    前情提要: Spark RPC框架源码分析(一)简述 一. Spark RPC概述 上一篇我们已经说明了Spark RPC框架的一个简单例子,Spark RPC相关的两个编程模型,Actor模型和Re ...

随机推荐

  1. java-tip-HashMap

    HashMap的基本查找过程: 先使用key.hashCode()生成哈希值,根据哈希值来确定key存放的位置 找到key在数组中的位置后,再使用key.equals()方法来找到指定的key. 1. ...

  2. Result Grouping / Field Collapsing-结果分组

    WiKi:http://wiki.apache.org/solr/FieldCollapsing Introduction 字段折叠和结果分组是考虑相同solr功能的两种不同的方式. 字段折叠折叠一组 ...

  3. redis 面试题1 有用

    1.什么是redis? Redis 是一个基于内存的高性能key-value数据库. 2.Reids的特点 Redis本质上是一个Key-Value类型的内存数据库,很像memcached,整个数据库 ...

  4. Tsung压力测试:Openfire

    环境准备 安装Tsung.安装openfire.安装Spark 要对openfire进行压力测试,因此我们主要讲解如何利用jabber_register.xml在openfire上面注册用户,以及利用 ...

  5. 开源项目spring-shiro-training思维导图

    写在前面 终于完成了一个开源项目的思维导图解读.选spring-shiro-training这个项目解读是因为它开源,然后涉及到了很多我们常用的技术,如缓存,权限,任务调度,ssm框架,Druid监控 ...

  6. cookie用法小结 cookie.setPath 跨域共享

    1. JSP中Cookie的读写 Cookie的本质是一个键值对,当浏览器访问web服务器的时候写入在客户端机器上,里面记录一些信息.Cookie还有一些附加信息,比如域名.有效时间.注释等等. 下面 ...

  7. Asp.net相关知识和经验的碎片化记录

    1.解决IIS7.0下“HTTP 错误 404.15 - Not Found 请求筛选模块被配置为拒绝包含的查询字符串过长的请求”问题 方案1:在程序的web.config中system.web节点里 ...

  8. jcabanillas/yii2-inspinia-asset composert 安装失败

    minimum-stability (root-only) 这定义了通过稳定性过滤包的默认行为.默认为 stable(稳定).因此如果你依赖于一个 dev(开发)包,你应该明确的进行定义. 对每个包的 ...

  9. CodeForces 474B Worms (水题,二分)

    题意:给定 n 堆数,然后有 m 个话询问,问你在哪一堆里. 析:这个题是一个二分题,但是有一个函数,可以代替写二分,lower_bound. 代码如下: #include<bits/stdc+ ...

  10. sersync服务搭建

    前言: 一.为什么要用Rsync+sersync架构? 1.sersync是基于Inotify开发的,类似于Inotify-tools的工具 2.sersync可以记录下被监听目录中发生变化的(包括增 ...