类关系图

图片.png

功能介绍

包路径java.util

功能描述: Collection 是最基本的集合接口,继承了Iterable**接口,一个 Collection 代表一组 Object,即 Collection 的元素, Java不提供直接继承自Collection的类,只提供继承于子接口(如List和set)。

Collection 接口存储一组不唯一,无序的对象

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements

源码解析

Iterable

Iterable接口只有三个方法,实现了这个接口的集合对象支持迭代,也就是可迭代的。

  1. /**
  2. * @since 1.5
  3. * @jls 14.14.2 The enhanced for statement
  4. */
  5. public interface Iterable<T> {
  6. /**
  7. * 返回对应类型的迭代器
  8. * Iterator我们一般叫顺序遍历迭代器,它就是提供迭代机制的对象
  9. * 具体如何迭代,都是Iterator接口规范的。
  10. * @return an Iterator.
  11. */
  12. Iterator<T> iterator();
  13. /**
  14. * 对集合元素执行传入函数
  15. * @since 1.8
  16. */
  17. default void forEach(Consumer<? super T> action) {
  18. Objects.requireNonNull(action);
  19. for (T t : this) {
  20. action.accept(t);
  21. }
  22. }
  23. /**
  24. * 返回可以并行遍历元素的迭代器,以适应现在cpu多核时代并行遍历的需求。
  25. * 简单说:分割,增加并行处理能力
  26. * {@code Iterable}.
  27. * @since 1.8
  28. */
  29. default Spliterator<T> spliterator() {
  30. return Spliterators.spliteratorUnknownSize(iterator(), 0);
  31. }
  32. }

Collection

  1. package java.util;
  2. import java.util.function.Predicate;
  3. import java.util.stream.Stream;
  4. import java.util.stream.StreamSupport;
  5. /**
  6. *
  7. * @param <E> the type of elements in this collection
  8. *
  9. * @author Josh Bloch
  10. * @author Neal Gafter
  11. * @see Set
  12. * @see List
  13. * @see Map
  14. * @see SortedSet
  15. * @see SortedMap
  16. * @see HashSet
  17. * @see TreeSet
  18. * @see ArrayList
  19. * @see LinkedList
  20. * @see Vector
  21. * @see Collections
  22. * @see Arrays
  23. * @see AbstractCollection
  24. * @since 1.2
  25. */
  26. public interface Collection<E> extends Iterable<E> {
  27. // Query Operations 查询操作
  28. /**
  29. * 返回该集合中元素的个数。如果超过了Integer.MAX_VALUE,那么返回Integer.MAX_VALUE
  30. * @return the number of elements in this collection
  31. */
  32. int size();
  33. /**
  34. * 集合判空,如果集合中没有元素返回true。
  35. * @return <tt>true</tt> if this collection contains no elements
  36. */
  37. boolean isEmpty();
  38. /**
  39. * 判断集合是否存在某元素
  40. * 如果集合中包含指定元素那么返回true。特别的,如果集合中也包含NULL元素的时候并且要查找的元素也是NULL的时候也返回true。
  41. * @param o element whose presence in this collection is to be tested
  42. * @return <tt>true</tt> if this collection contains the specified
  43. */
  44. boolean contains(Object o);
  45. /**
  46. * 返回迭代器
  47. * @return an <tt>Iterator</tt> over the elements in this collection
  48. */
  49. Iterator<E> iterator();
  50. /**
  51. * 将集合转化为数组,返回包含此集合中所有元素的数组。
  52. * @return an array containing all of the elements in this collection
  53. */
  54. Object[] toArray();
  55. /**
  56. * 将集合转化为数组,返回集合中所有元素到传入的数组中
  57. * 该方法可以对返回的数组类型进行精确控制,而非像toArray方法一样返回Object[]
  58. *
  59. * @param <T> the runtime type of the array to contain the collection
  60. * @param a the array into which the elements of this collection are to be
  61. * stored, if it is big enough; otherwise, a new array of the same
  62. * runtime type is allocated for this purpose.
  63. * @return an array containing all of the elements in this collection
  64. */
  65. <T> T[] toArray(T[] a);
  66. // Modification Operations 更新操作
  67. /**
  68. * 向集合中添加一个元素。
  69. * 集合添加成功返回true,如果该集合不允许重复并且已经包含指定的元素。返回false
  70. * @param e element whose presence in this collection is to be ensured
  71. * @return <tt>true</tt> if this collection changed as a result of the
  72. * call
  73. */
  74. boolean add(E e);
  75. /**
  76. * 删除集合中的指定的元素。如果存在NULL,也删除。
  77. * @param o element to be removed from this collection, if present
  78. * @return <tt>true</tt> if an element was removed as a result of this call
  79. *
  80. */
  81. boolean remove(Object o);
  82. // Bulk Operations 大量数据操作
  83. /**
  84. * 如果该集合中包含指定集合中的所有元素的时候返回true。
  85. * @param c collection to be checked for containment in this collection
  86. * @return <tt>true</tt> if this collection contains all of the elements
  87. * in the specified collection
  88. *
  89. * @see #contains(Object)
  90. */
  91. boolean containsAll(Collection<?> c);
  92. /**
  93. * 将指定集合中的所有元素添加到此集合中。
  94. * 在添加过程中如果被添加的集合发生了更改,addAll方法不具有幂等性。
  95. * @param c collection containing elements to be added to this collection
  96. * @return <tt>true</tt> if this collection changed as a result of the call
  97. *
  98. * @see #add(Object)
  99. */
  100. boolean addAll(Collection<? extends E> c);
  101. /**
  102. * 删除当前集合中所有等于指定集合中的元素。
  103. * @param c collection containing elements to be removed from this collection
  104. * @return <tt>true</tt> if this collection changed as a result of the
  105. * call
  106. * @see #remove(Object)
  107. * @see #contains(Object)
  108. */
  109. boolean removeAll(Collection<?> c);
  110. /**
  111. * 删除所有匹配过滤器Predicate条件的元素
  112. * @param filter a predicate which returns {@code true} for elements to be
  113. * removed
  114. * @return {@code true} if any elements were removed
  115. * @since 1.8
  116. */
  117. default boolean removeIf(Predicate<? super E> filter) {
  118. // 校验lambda是否为空
  119. Objects.requireNonNull(filter);
  120. boolean removed = false;
  121. // 获取迭代器
  122. final Iterator<E> each = iterator();
  123. while (each.hasNext()) {
  124. // 如果该方法执行返回true则移除该元素
  125. if (filter.test(each.next())) {
  126. each.remove();
  127. removed = true;
  128. }
  129. }
  130. return removed;
  131. }
  132. /**
  133. * 仅保留该指定集合中存在的所有元素。其余删除
  134. * @param c collection containing elements to be retained in this collection
  135. * @return <tt>true</tt> if this collection changed as a result of the call
  136. *
  137. * @see #remove(Object)
  138. * @see #contains(Object)
  139. */
  140. boolean retainAll(Collection<?> c);
  141. /**
  142. * 清空掉集合中的所有元素
  143. */
  144. void clear();
  145. // Comparison and hashing
  146. /**
  147. * 比较是否相等
  148. * @see Object#equals(Object)
  149. * @see Set#equals(Object)
  150. * @see List#equals(Object)
  151. */
  152. boolean equals(Object o);
  153. /**
  154. *
  155. * @return the hash code value for this collection
  156. *
  157. * @see Object#hashCode()
  158. * @see Object#equals(Object)
  159. */
  160. int hashCode();
  161. /**
  162. * 返回Spliterator分割器,用于并发流式处理的时候调用
  163. * @return a {@code Spliterator} over the elements in this collection
  164. * @since 1.8
  165. */
  166. @Override
  167. default Spliterator<E> spliterator() {
  168. return Spliterators.spliterator(this, 0);
  169. }
  170. /**
  171. * 返回流对象
  172. * @return a sequential {@code Stream} over the elements in this collection
  173. * @since 1.8
  174. */
  175. default Stream<E> stream() {
  176. return StreamSupport.stream(spliterator(), false);
  177. }
  178. /**
  179. * 返回并发流式对象
  180. * @return a possibly parallel {@code Stream} over the elements in this
  181. * collection
  182. * @since 1.8
  183. */
  184. default Stream<E> parallelStream() {
  185. return StreamSupport.stream(spliterator(), true);
  186. }
  187. }

AbstractCollection

直接实现Collection接口的抽象类,实现基本方法,方便子类实现Collection功能

  1. public abstract class AbstractCollection<E> implements Collection<E> {
  2. /**
  3. *
  4. */
  5. protected AbstractCollection() {
  6. }
  7. // Query Operations
  8. /**
  9. * 返回迭代器
  10. * @return an iterator over the elements contained in this collection
  11. */
  12. public abstract Iterator<E> iterator();
  13. // 获取集合元素总数
  14. public abstract int size();
  15. /**
  16. * 判断集合是否为空
  17. */
  18. public boolean isEmpty() {
  19. return size() == 0;
  20. }
  21. /**
  22. * 判断元素是否存在于集合之中
  23. */
  24. public boolean contains(Object o) {
  25. Iterator<E> it = iterator();
  26. if (o==null) {
  27. while (it.hasNext())
  28. if (it.next()==null)
  29. return true;
  30. } else {
  31. while (it.hasNext())
  32. if (o.equals(it.next()))
  33. return true;
  34. }
  35. return false;
  36. }
  37. /**
  38. * 将集合转为数组
  39. */
  40. public Object[] toArray() {
  41. // Estimate size of array; be prepared to see more or fewer elements
  42. // 新建同等大小的Object数组
  43. Object[] r = new Object[size()];
  44. Iterator<E> it = iterator();
  45. // 遍历并填充元素
  46. for (int i = 0; i < r.length; i++) {
  47. if (! it.hasNext()) // fewer elements than expected
  48. return Arrays.copyOf(r, i);
  49. r[i] = it.next();
  50. }
  51. // it.hasNext方法为true表明数组长度不足【可能在转换过程中有别的线程往里面加了元素】
  52. // 调用finishToArray对数组进行扩容并完成转换
  53. return it.hasNext() ? finishToArray(r, it) : r;
  54. }
  55. /**
  56. * 将集合转为数组
  57. */
  58. @SuppressWarnings("unchecked")
  59. public <T> T[] toArray(T[] a) {
  60. // Estimate size of array; be prepared to see more or fewer elements
  61. int size = size();
  62. // 构造足够大的数组
  63. T[] r = a.length >= size ? a :
  64. (T[])java.lang.reflect.Array
  65. .newInstance(a.getClass().getComponentType(), size);
  66. Iterator<E> it = iterator();
  67. // 遍历并填充元素
  68. for (int i = 0; i < r.length; i++) {
  69. if (! it.hasNext()) { // fewer elements than expected
  70. if (a == r) {
  71. r[i] = null; // null-terminate
  72. } else if (a.length < i) {
  73. return Arrays.copyOf(r, i);
  74. } else {
  75. System.arraycopy(r, 0, a, 0, i);
  76. if (a.length > i) {
  77. a[i] = null;
  78. }
  79. }
  80. return a;
  81. }
  82. r[i] = (T)it.next();
  83. }
  84. // more elements than expected
  85. // it.hasNext方法为true表明数组长度不足【可能在转换过程中有别的线程往里面加了元素】
  86. // 调用finishToArray对数组进行扩容并完成转换
  87. return it.hasNext() ? finishToArray(r, it) : r;
  88. }
  89. /**
  90. * 最大数组容量限制
  91. */
  92. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  93. /**
  94. * 数组扩容
  95. * (1)当数组索引指向最后一个元素+1时,对数组进行扩容:即创建一个更长的数组,然后将原数组的内容复制到新数组中
  96. * (2)扩容大小:cap + cap/2 +1
  97. * (3)扩容前需要先判断数组长度是否溢出
  98. * 注意:这里的迭代器是从上层的方法(toArray)传过来的,并且这个迭代器已执行了一部分,而不是从头开始迭代的
  99. * @param r the array, replete with previously stored elements
  100. * @param it the in-progress iterator over this collection
  101. * @return array containing the elements in the given array, plus any
  102. * further elements returned by the iterator, trimmed to size
  103. */
  104. @SuppressWarnings("unchecked")
  105. private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
  106. int i = r.length;
  107. while (it.hasNext()) {
  108. int cap = r.length;
  109. if (i == cap) {
  110. int newCap = cap + (cap >> 1) + 1;
  111. // overflow-conscious code
  112. if (newCap - MAX_ARRAY_SIZE > 0)
  113. newCap = hugeCapacity(cap + 1);
  114. r = Arrays.copyOf(r, newCap);
  115. }
  116. r[i++] = (T)it.next();
  117. }
  118. // trim if overallocated
  119. return (i == r.length) ? r : Arrays.copyOf(r, i);
  120. }
  121. /**
  122. * 判断数组容量是否溢出,最大为整型数据的最大值
  123. */
  124. private static int hugeCapacity(int minCapacity) {
  125. if (minCapacity < 0) // overflow
  126. throw new OutOfMemoryError
  127. ("Required array size too large");
  128. return (minCapacity > MAX_ARRAY_SIZE) ?
  129. Integer.MAX_VALUE :
  130. MAX_ARRAY_SIZE;
  131. }
  132. // Modification Operations
  133. /**
  134. * 未移除指定元素实现
  135. */
  136. public boolean add(E e) {
  137. throw new UnsupportedOperationException();
  138. }
  139. /**
  140. * 移除指定元素
  141. */
  142. public boolean remove(Object o) {
  143. Iterator<E> it = iterator();
  144. if (o==null) {
  145. while (it.hasNext()) {
  146. if (it.next()==null) {
  147. it.remove();
  148. return true;
  149. }
  150. }
  151. } else {
  152. while (it.hasNext()) {
  153. if (o.equals(it.next())) {
  154. it.remove();
  155. return true;
  156. }
  157. }
  158. }
  159. return false;
  160. }
  161. // Bulk Operations
  162. /**
  163. * 如果该集合中包含指定集合中的所有元素的时候返回true。
  164. * @see #contains(Object)
  165. */
  166. public boolean containsAll(Collection<?> c) {
  167. for (Object e : c)
  168. if (!contains(e))
  169. return false;
  170. return true;
  171. }
  172. /**
  173. * 遍历参数集合,依次将参数集合中的元素添加当前集合中
  174. * @see #add(Object)
  175. */
  176. public boolean addAll(Collection<? extends E> c) {
  177. boolean modified = false;
  178. for (E e : c)
  179. if (add(e))
  180. modified = true;
  181. return modified;
  182. }
  183. /**
  184. * 移除参数集合的元素
  185. * @see #remove(Object)
  186. * @see #contains(Object)
  187. */
  188. public boolean removeAll(Collection<?> c) {
  189. Objects.requireNonNull(c);
  190. boolean modified = false;
  191. Iterator<?> it = iterator();
  192. while (it.hasNext()) {
  193. if (c.contains(it.next())) {
  194. it.remove();
  195. modified = true;
  196. }
  197. }
  198. return modified;
  199. }
  200. /**
  201. * 仅保留该指定集合中存在的所有元素。其余删除
  202. * @see #remove(Object)
  203. * @see #contains(Object)
  204. */
  205. public boolean retainAll(Collection<?> c) {
  206. Objects.requireNonNull(c);
  207. boolean modified = false;
  208. Iterator<E> it = iterator();
  209. while (it.hasNext()) {
  210. if (!c.contains(it.next())) {
  211. it.remove();
  212. modified = true;
  213. }
  214. }
  215. return modified;
  216. }
  217. /**
  218. * 删除所有元素
  219. */
  220. public void clear() {
  221. Iterator<E> it = iterator();
  222. while (it.hasNext()) {
  223. it.next();
  224. it.remove();
  225. }
  226. }
  227. // String conversion
  228. /**
  229. * 重载toString方法
  230. * @return a string representation of this collection
  231. */
  232. public String toString() {
  233. Iterator<E> it = iterator();
  234. if (! it.hasNext())
  235. return "[]";
  236. StringBuilder sb = new StringBuilder();
  237. sb.append('[');
  238. for (;;) {
  239. E e = it.next();
  240. sb.append(e == this ? "(this Collection)" : e);
  241. if (! it.hasNext())
  242. return sb.append(']').toString();
  243. sb.append(',').append(' ');
  244. }
  245. }
  246. }

简单使用

package com.java.list;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @description Collection接口演示
 * @auther: lai.guanfu
 * @date: 2021-01-04 22:51
 */
public class CollectionCode {
    public static void main(String[] args) {
        Collection<Integer> collection = new ArrayList<>();
        for(int i=0;i<20;i++){
            collection.add(i);
        }
        System.out.println(collection);
        System.out.println();

        // ============= 移除大于10的元素

        // 传统写法:
//        Iterator<Integer> iterator = collection.iterator();
//        while (iterator.hasNext()) {
//            Integer item = iterator.next();
//            if (item > 10)
//                iterator.remove();
//        }

        // removeIf调用
        collection.removeIf(item -> item>10);
        System.out.println(collection);
    }
}

输出如下:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

总结

  • Collection 是最基本的集合接口,继承了Iterable接口,一个 Collection 代表一组 Object,即 Collection 的元素, Java不提供直接继承自Collection的类,只提供继承于子接口(如List和set)
  • Collection 接口存储一组不唯一,无序的对象
  • 在Collection中定义了一些常用的接口,供子类去实现
  • 在JDK1.8中新增了一些方法,例如获取获取流式函数的方法在这个接口中引入了default方法