Java Collection源码总结 Collection源码注释翻译和解析中英文对照版

版本
JDK8(JDK1.8)

Collection接口源码重点
1.集合层次结构中的根接口,集合表示一组对象,称为其元素,某些集合允许重复元素,而其他集合则不允许,有些是有序的,有些是无序的。

2.该接口类定义了各种规范包括方法规范和抛出异常的规范,还有比较和哈希操作,以及分离器spliterator和流stream,方法主要有三类查询、修改、批量,如contains(Object o)、add(E e)、addAll(Collection<? extends E> c)分别对应查询、修改、批量

3.接口定义的部分集合操作方法

方法名作用
boolean isEmpty()判断集合是否为空
Object[] toArray()按照迭代器迭代顺序返回元素数组
boolean add(E e)添加元素
boolean addAll(Collection<? extends E> c)将c中所有元素添加进集合
boolean remove(Object o)移除元素
boolean removeAll(Collection<?> c)从集合中移除c中的元素
boolean contains(Object o)判断o是否在集合中
boolean containsAll(Collection<?> c)c中所有元素都在集合中返回true否则false
boolean retainAll(Collection<?> c)删除集合中元素,只保留c中也有的元素
void clear()删除集合中所有元素

remove(.)方法还有一个变种 boolean removeIf(Predicate<? super E> filter),
根据Predicate定义的规则来删除集合的元素,可以看我这篇文章 Predicate

4.接口定义的部分其他方法

方法名作用
boolean equals(Object o)Object.equals实现是引用比较,可以重写为值比较
int hashCode()应满足c1.equals(c2)表示c1.hashCode()==c2.hashCode()
Iterator iterator()返回迭代器
Stream stream()返回流
Stream parallelStream()返回并行流
Spliterator spliterator()返回分离器

5.接口定义的抛出异常

异常名意义
UnsupportedOperationException此集合不支持添加操作
ClassCastException传入元素的类与该集合不兼容
NullPointerException传入的元素为null,并且此集合不允许null元素
IllegalArgumentException元素的某些属性阻止将其添加到此集合
IllegalStateException由于插入限制,此时无法添加元素(容器已满)

Collection接口源码

package java.util;

import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * The root interface in the <i>collection hierarchy</i>.  A collection
 * represents a group of objects, known as its <i>elements</i>.  Some
 * collections allow duplicate elements and others do not.  Some are ordered
 * and others unordered.  The JDK does not provide any <i>direct</i>
 * implementations of this interface: it provides implementations of more
 * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>.  This interface
 * is typically used to pass collections around and manipulate them where
 * maximum generality is desired.
 * 集合层次结构中的根接口。集合表示一组对象,称为其元素。
 * 某些集合允许重复元素,而其他集合则不允许。
 * 有些是有序的,有些是无序的。JDK不提供此接口的任何直接实现:
 * 它提供更具体的子接口(如Set和List)的实现。
 * 此接口通常用于传递集合,并在需要最大通用性的地方对其进行操作。
 * 
 *
 * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
 * duplicate elements) should implement this interface directly.
 * 包或多集(可能包含重复元素的无序集合)应直接实现此接口
 *
 * 
 * 
 * <p>All general-purpose <tt>Collection</tt> implementation classes (which
 * typically implement <tt>Collection</tt> indirectly through one of its
 * subinterfaces) should provide two "standard" constructors: a void (no
 * arguments) constructor, which creates an empty collection, and a
 * constructor with a single argument of type <tt>Collection</tt>, which
 * creates a new collection with the same elements as its argument.  In
 * effect, the latter constructor allows the user to copy any collection,
 * producing an equivalent collection of the desired implementation type.
 * There is no way to enforce this convention (as interfaces cannot contain
 * constructors) but all of the general-purpose <tt>Collection</tt>
 * implementations in the Java platform libraries comply.
 * 所有通用集合实现类(通常通过其子接口之一间接实现集合)都应提供两个“标准”构造函数:
 * 一个创建空集合的void(无参数)构造函数和一个具有Collection类型的单个参数的构造函数,
 * 它创建一个新集合,该集合的元素与其参数相同。
 * 实际上,后一个构造函数允许用户复制任何集合,从而生成所需实现类型的等效集合。
 * 无法强制执行此约定(因为接口不能包含构造函数),但Java平台库中的所有通用集合实现都符合此约定。
 * 
 * 
 * 
 * 
 *
 * <p>The "destructive" methods contained in this interface, that is, the
 * methods that modify the collection on which they operate, are specified to
 * throw <tt>UnsupportedOperationException</tt> if this collection does not
 * support the operation.  If this is the case, these methods may, but are not
 * required to, throw an <tt>UnsupportedOperationException</tt> if the
 * invocation would have no effect on the collection.  For example, invoking
 * the {@link #addAll(Collection)} method on an unmodifiable collection may,
 * but is not required to, throw the exception if the collection to be added
 * is empty.
 * 
 * 此接口中包含的“破坏性”方法,即修改其操作的集合的方法,
 * 指定在该集合不支持该操作时引发UnsupportedOperationException。
 * 如果是这种情况,如果调用对集合没有影响,则这些方法可能(但不是必需)
 * 抛出UnsupportedOperationException。例如,如果要添加的集合为空,
 * 则对不可修改的集合调用addAll(Collection)方法可能(但不是必需)引发异常。
 * 
 * 
 * 
 * 
 * <p><a name="optional-restrictions">
 * Some collection implementations have restrictions on the elements that
 * they may contain.</a>  For example, some implementations prohibit null elements,
 * and some have restrictions on the types of their elements.  Attempting to
 * add an ineligible element throws an unchecked exception, typically
 * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.  Attempting
 * to query the presence of an ineligible element may throw an exception,
 * or it may simply return false; some implementations will exhibit the former
 * behavior and some will exhibit the latter.  More generally, attempting an
 * operation on an ineligible element whose completion would not result in
 * the insertion of an ineligible element into the collection may throw an
 * exception or it may succeed, at the option of the implementation.
 * Such exceptions are marked as "optional" in the specification for this
 * interface.
 * 某些集合实现对它们可能包含的元素有限制。
 * 例如,有些实现禁止空元素,有些实现对其元素的类型有限制。
 * 尝试添加不合格的元素会引发未经检查的异常,通常为NullPointerException或ClassCastException。
 * 试图查询不合格元素的存在可能会引发异常,或者只返回false;
 * 有些实现将展示前一种行为,有些实现将展示后一种行为。
 * 更一般地说,在不合格元素上尝试操作(其完成不会导致将不合格元素插入到集合中)可能会引发异常,
 * 或者可能会成功(由实现选择)。此类异常在该接口规范中标记为“可选”。
 * 
 * 
 * 
 * 
 * 
 * <p>It is up to each collection to determine its own synchronization
 * policy.  In the absence of a stronger guarantee by the
 * implementation, undefined behavior may result from the invocation
 * of any method on a collection that is being mutated by another
 * thread; this includes direct invocations, passing the collection to
 * a method that might perform invocations, and using an existing
 * iterator to examine the collection.
 * 由每个集合决定其自己的同步策略。在实现没有更强有力的保证的情况下,
 * 未定义的行为可能是由于调用另一个线程正在变异的集合上的任何方法而导致的;
 * 这包括直接调用、将集合传递给可能执行调用的方法以及使用现有迭代器检查集合。
 * 
 * 
 * 
 * 
 *
 * <p>Many methods in Collections Framework interfaces are defined in
 * terms of the {@link Object#equals(Object) equals} method.  For example,
 * the specification for the {@link #contains(Object) contains(Object o)}
 * method says: "returns <tt>true</tt> if and only if this collection
 * contains at least one element <tt>e</tt> such that
 * <tt>(o==null ? e==null : o.equals(e))</tt>."  This specification should
 * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>
 * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be
 * invoked for any element <tt>e</tt>.  Implementations are free to implement
 * optimizations whereby the <tt>equals</tt> invocation is avoided, for
 * example, by first comparing the hash codes of the two elements.  (The
 * {@link Object#hashCode()} specification guarantees that two objects with
 * unequal hash codes cannot be equal.)  More generally, implementations of
 * the various Collections Framework interfaces are free to take advantage of
 * the specified behavior of underlying {@link Object} methods wherever the
 * implementor deems it appropriate.
 * 集合框架接口中的许多方法都是根据Object.equals(Object)方法定义的。
 * 例如,contains(Object o)方法的规范说:“当且仅当此集合至少包含一个元素e,
 * 使得 (o==null?e==null:o.equals(e))返回true。”
 * 此规范不应解释为暗示使用非null参数o调用Collection.contains
 * 将导致对任何元素e调用o.equals(e)。
 * 实现可以自由地实现优化,从而避免equals调用,例如,首先比较两个元素的哈希代码。
 * Object.hashCode()规范保证两个散列码不相等的对象不能相等。
 * 更一般地说,各种集合框架接口的实现可以在实现者认为合适的地方自由地利用底层Object方法的指定行为。
 * 
 * 
 * 
 * 
 * 
 *
 * <p>Some collection operations which perform recursive traversal of the
 * collection may fail with an exception for self-referential instances where
 * the collection directly or indirectly contains itself. This includes the
 * {@code clone()}, {@code equals()}, {@code hashCode()} and {@code toString()}
 * methods. Implementations may optionally handle the self-referential scenario,
 * however most current implementations do not do so.
 * 执行递归遍历集合的某些集合操作可能会失败,但对于集合直接或间接包含自身的自引用实例,
 * 则会出现例外。这包括clone()、equals()、hashCode()和toString()方法。
 * 实现可以选择性地处理自引用场景,但是大多数当前实现不这样做。
 * 
 * 
 *
 * <p>This interface is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @implSpec
 * The default method implementations (inherited or otherwise) do not apply any
 * synchronization protocol.  If a {@code Collection} implementation has a
 * specific synchronization protocol, then it must override default
 * implementations to apply that protocol.
 * 默认方法实现(继承或其他)不应用任何同步协议,如果Collection实现具有特定的同步协议,
 * 则它必须覆盖默认实现以应用该协议。
 *
 * @param <E> the type of elements in this collection
 *
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @see     Set
 * @see     List
 * @see     Map
 * @see     SortedSet
 * @see     SortedMap
 * @see     HashSet
 * @see     TreeSet
 * @see     ArrayList
 * @see     LinkedList
 * @see     Vector
 * @see     Collections
 * @see     Arrays
 * @see     AbstractCollection
 * @since 1.2
 */

public interface Collection<E> extends Iterable<E> {
    // Query Operations  查询操作

    /**
     * Returns the number of elements in this collection.  If this collection
     * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     * 返回此集合中的元素数。如果此集合包含超过Integer.MAX_VALUE个元素,则返回Integer.MAX_VALUE
     *
     * @return the number of elements in this collection
     */
    int size();

    /**
     * Returns <tt>true</tt> if this collection contains no elements.
     * 如果此集合不包含任何元素,则返回true。
     *
     * @return <tt>true</tt> if this collection contains no elements
     */
    boolean isEmpty();

    /**
     * Returns <tt>true</tt> if this collection contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this collection
     * contains at least one element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     * 如果此集合包含指定的元素,则返回true。更正式地说,当且仅当此集合包含至少一个元素e,
     * 且(o==null ? e==null:o.equals(e))时,返回true。
     * 即 如果o等于null 则判断e是否等于null,如果o不等于null,则使用o.equals(e)判断是否相等
     * 
     *
     * @param o element whose presence in this collection is to be tested 要测试其在此集合中的存在的元素
     * @return <tt>true</tt> if this collection contains the specified
     *         element 如果此集合包含指定的元素,则为true
     * @throws ClassCastException if the type of the specified element
     *         is incompatible with this collection 如果指定元素的类型与此集合不兼容
     *         (<a href="#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified element is null and this
     *         collection does not permit null elements 如果指定的元素为null,并且此集合不允许null元素
     *         (<a href="#optional-restrictions">optional</a>)
     */
    boolean contains(Object o);

    /**
     * Returns an iterator over the elements in this collection.  There are no
     * guarantees concerning the order in which the elements are returned
     * (unless this collection is an instance of some class that provides a
     * guarantee).
     * 返回此集合中元素的迭代器。
     * 对于元素的返回顺序没有任何保证(除非此集合是提供有序保证的某个类的实例)。
     *
     * @return an <tt>Iterator</tt> over the elements in this collection 此集合中元素的迭代器
     */
    Iterator<E> iterator();

    /**
     * Returns an array containing all of the elements in this collection.
     * If this collection makes any guarantees as to what order its elements
     * are returned by its iterator, this method must return the elements in
     * the same order.
     * 返回包含此集合中所有元素的数组。如果此集合保证其迭代器返回其元素的顺序,
     * 则此方法必须以同样的顺序。
     * 
     * 
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this collection.  (In other words, this method must
     * allocate a new array even if this collection is backed by an array).
     * The caller is thus free to modify the returned array.
     * 返回的数组将是“安全的”,因为此集合不维护对它的引用。
     * (换句话说,即使此集合由数组支持,此方法也必须分配新数组)。因此,调用者可以自由修改返回的数组。
     * 
     *
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.  此方法充当数组的API和集合的API之间的桥梁。
     *
     * @return an array containing all of the elements in this collection
     * 包含此集合中所有元素的数组
     */
    Object[] toArray();

    /**
     * Returns an array containing all of the elements in this collection;
     * the runtime type of the returned array is that of the specified array.
     * If the collection fits in the specified array, it is returned therein.
     * Otherwise, a new array is allocated with the runtime type of the
     * specified array and the size of this collection.
     * 返回包含此集合中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
     * 如果集合适合指定的数组,则返回所有元素在给定数组其中。
     * 否则,将使用指定数组的运行时类型和此集合的大小分配一个新数组。
     *
     * 
     * 
     * 
     * 
     * <p>If this collection fits in the specified array with room to spare
     * (i.e., the array has more elements than this collection), the element
     * in the array immediately following the end of the collection is set to
     * <tt>null</tt>.  (This is useful in determining the length of this
     * collection <i>only</i> if the caller knows that this collection does
     * not contain any <tt>null</tt> elements.)
     * 如果此集合适合具有空闲空间的指定数组(即,该数组的元素多于此集合),
     * 则紧跟在集合结束后的数组中的元素将设置为null。
     * (仅当调用方知道此集合不包含任何空元素时,这在确定此集合的长度时才有用。)
     * 
     * 
     *
     * <p>If this collection makes any guarantees as to what order its elements
     * are returned by its iterator, this method must return the elements in
     * the same order. 如果此集合保证迭代器返回元素的顺序,则此方法必须以相同的顺序返回元素
     *
     * <p>Like the {@link #toArray()} method, this method acts as bridge between
     * array-based and collection-based APIs.  Further, this method allows
     * precise control over the runtime type of the output array, and may,
     * under certain circumstances, be used to save allocation costs.
     * 与toArray()方法一样,此方法充当数组的API和集合的API之间的桥梁。
     * 此外,此方法允许对输出数组的运行时类型进行精确控制,并且在某些情况下可用于节省分配成本。
     * 
     *
     * <p>Suppose <tt>x</tt> is a collection known to contain only strings.
     * The following code can be used to dump the collection into a newly
     * allocated array of <tt>String</tt>: 
     * 假设x是已知仅包含字符串的集合。以下代码可用于将集合转储到新分配的字符串数组中
     *
     * <pre>
     *     String[] y = x.toArray(new String[0]);</pre>
     *
     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
     * <tt>toArray()</tt>.
     * 请注意,toArray(new Object[0])与toArray()完全相同。
     *
     * @param <T> the runtime type of the array to contain the collection 包含集合的数组的运行时类型
     * @param a the array into which the elements of this collection are to be
     *        stored, if it is big enough; otherwise, a new array of the same
     *        runtime type is allocated for this purpose.
     *       a此集合的元素将存储到的数组(如果足够大);否则,将为此目的分配相同运行时类型的新数组。
     * @return an array containing all of the elements in this collection 包含此集合中所有元素的数组
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this collection
     *          如果指定数组的运行时类型不是此集合中每个元素的运行时类型的超类型
     * @throws NullPointerException if the specified array is null 如果指定的数组为空
     */
    <T> T[] toArray(T[] a);

    // Modification Operations 修改操作

    /**
     * Ensures that this collection contains the specified element (optional
     * operation).  Returns <tt>true</tt> if this collection changed as a
     * result of the call.  (Returns <tt>false</tt> if this collection does
     * not permit duplicates and already contains the specified element.)<p>
     * 确保此集合包含指定的元素(可选操作)。如果此集合因调用而更改,则返回true。
     * (如果此集合不允许重复并且已包含指定元素,则返回false。)
     * 
     * 
     * 
     *
     * Collections that support this operation may place limitations on what
     * elements may be added to this collection.  In particular, some
     * collections will refuse to add <tt>null</tt> elements, and others will
     * impose restrictions on the type of elements that may be added.
     * Collection classes should clearly specify in their documentation any
     * restrictions on what elements may be added.<p>
     * 支持此操作的集合可能会对可添加到此集合的元素设置限制。
     * 特别是,一些集合将拒绝添加null元素,而其他集合将对可能添加的元素类型施加限制。
     * 集合类应在其文档中明确指定对可能添加的元素的任何限制。
     * 
     * 
     * 
     *
     * If a collection refuses to add a particular element for any reason
     * other than that it already contains the element, it <i>must</i> throw
     * an exception (rather than returning <tt>false</tt>).  This preserves
     * the invariant that a collection always contains the specified element
     * after this call returns.
     * 如果集合由于任何原因拒绝添加特定元素,而不是因为它已经包含该元素,
     * 则它必须抛出异常(而不是返回false)。
     * 这保留了在调用返回后集合始终包含指定元素的不变量。
     * 
     * 
     *
     * @param e element whose presence in this collection is to be ensured 要确保其在此集合中存在的元素(要添加进集合的元素)
     * @return <tt>true</tt> if this collection changed as a result of the
     *         call 如果此集合因调用而更改,则为true
     * @throws UnsupportedOperationException if the <tt>add</tt> operation
     *         is not supported by this collection 如果此集合不支持添加操作
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this collection 如果指定元素的类阻止将其添加到此集合
     * @throws NullPointerException if the specified element is null and this
     *         collection does not permit null elements 如果指定的元素为null,并且此集合不允许null元素
     * @throws IllegalArgumentException if some property of the element
     *         prevents it from being added to this collection 如果元素的某些属性阻止将其添加到此集合
     * @throws IllegalStateException if the element cannot be added at this
     *         time due to insertion restrictions 如果由于插入限制,此时无法添加元素(容器已满)
     */
    boolean add(E e);

    /**
     * Removes a single instance of the specified element from this
     * collection, if it is present (optional operation).  More formally,
     * removes an element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if
     * this collection contains one or more such elements.  Returns
     * <tt>true</tt> if this collection contained the specified element (or
     * equivalently, if this collection changed as a result of the call).
     * 从该集合中删除指定元素的单个实例(如果存在)(可选操作)。
     * 更正式地说,如果此集合包含一个或多个这样的元素,则删除元素e,
     * 以便(o==null?e==null:o.equals(e))。
     * 如果此集合包含指定的元素,则返回true(如果此集合因调用而更改,则返回等效值)。
     * 
     * 
     *
     * @param o element to be removed from this collection, if present 要从此集合中删除的元素(如果存在)
     * @return <tt>true</tt> if an element was removed as a result of this call 如果此调用导致元素被删除,则为true
     * @throws ClassCastException if the type of the specified element
     *         is incompatible with this collection
     *         (<a href="#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified element is null and this
     *         collection does not permit null elements
     *         (<a href="#optional-restrictions">optional</a>)
     * @throws UnsupportedOperationException if the <tt>remove</tt> operation
     *         is not supported by this collection 如果此集合不支持删除操作
     */
    boolean remove(Object o);


    // Bulk Operations 批量操作

    /**
     * Returns <tt>true</tt> if this collection contains all of the elements
     * in the specified collection.
     * 如果此集合包含指定集合中的所有元素,则返回true。
     *
     * @param  c collection to be checked for containment in this collection 要检查此集合中是否包含的集合
     * @return <tt>true</tt> if this collection contains all of the elements
     *         in the specified collection 如果此集合包含指定集合中的所有元素,则为true
     * @throws ClassCastException if the types of one or more elements
     *         in the specified collection are incompatible with this
     *         collection
     *         (<a href="#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified collection contains one
     *         or more null elements and this collection does not permit null
     *         elements
     *         (<a href="#optional-restrictions">optional</a>),
     *         or if the specified collection is null.
     * @see    #contains(Object)
     */
    boolean containsAll(Collection<?> c);

    /**
     * Adds all of the elements in the specified collection to this collection
     * (optional operation).  The behavior of this operation is undefined if
     * the specified collection is modified while the operation is in progress.
     * (This implies that the behavior of this call is undefined if the
     * specified collection is this collection, and this collection is
     * nonempty.)
     * 将指定集合中的所有元素添加到此集合(可选操作)。
     * 如果在操作进行过程中修改了指定的集合,则此操作的行为未定义。
     * (这意味着如果指定的集合是此集合,并且此集合是非空的,则此调用的行为是未定义的。)
     * 即传入的集合c是自己即addAll(this)这样会导致未知行为发生
     * 
     * 
     * 
     *
     * @param c collection containing elements to be added to this collection c 包含要添加到此集合的元素的集合
     * @return <tt>true</tt> if this collection changed as a result of the call 如果此集合因调用而更改,则为true
     * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
     *         is not supported by this collection
     * @throws ClassCastException if the class of an element of the specified
     *         collection prevents it from being added to this collection
     * @throws NullPointerException if the specified collection contains a
     *         null element and this collection does not permit null elements,
     *         or if the specified collection is null
     * @throws IllegalArgumentException if some property of an element of the
     *         specified collection prevents it from being added to this
     *         collection
     * @throws IllegalStateException if not all the elements can be added at
     *         this time due to insertion restrictions
     * @see #add(Object)
     */
    boolean addAll(Collection<? extends E> c);

    /**
     * Removes all of this collection's elements that are also contained in the
     * specified collection (optional operation).  After this call returns,
     * this collection will contain no elements in common with the specified
     * collection.
     * 删除指定集合中也包含的此集合的所有元素(可选操作)。
     * 此调用返回后,此集合将不包含与指定集合相同的元素
     * 
     * @param c collection containing elements to be removed from this collection c包含要从此集合中删除的元素的集合
     * @return <tt>true</tt> if this collection changed as a result of the
     *         call 如果此集合因调用而更改,则为true
     * @throws UnsupportedOperationException if the <tt>removeAll</tt> method
     *         is not supported by this collection
     * @throws ClassCastException if the types of one or more elements
     *         in this collection are incompatible with the specified
     *         collection
     *         (<a href="#optional-restrictions">optional</a>)
     * @throws NullPointerException if this collection contains one or more
     *         null elements and the specified collection does not support
     *         null elements
     *         (<a href="#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see #remove(Object)
     * @see #contains(Object)
     */
    boolean removeAll(Collection<?> c);

    /**
     * Removes all of the elements of this collection that satisfy the given
     * predicate.  Errors or runtime exceptions thrown during iteration or by
     * the predicate are relayed to the caller.
     * 删除此集合中满足给定Predicate的所有元素。
     * 迭代期间或Predicate引发的错误或运行时异常将转发给调用方。
     * 
     *
     * 
     * @implSpec
     * The default implementation traverses all elements of the collection using
     * its {@link #iterator}.  Each matching element is removed using
     * {@link Iterator#remove()}.  If the collection's iterator does not
     * support removal then an {@code UnsupportedOperationException} will be
     * thrown on the first matching element.
     * 默认实现使用其iterator遍历集合的所有元素。
     * 使用iterator.remove()删除每个匹配元素。
     * 如果集合的迭代器不支持删除,那么将在第一个匹配元素上抛出UnsupportedOperationException。
     * 
     * predicate 相对于某种匹配规则,传递元素进去返回true或false,分别表示符合规则,不符合规则
     *
     * @param filter a predicate which returns {@code true} for elements to be
     *        removed 会删除传入predicate且返回了true的元素,predicate是匹配规则
     * @return {@code true} if any elements were removed
     * @throws NullPointerException if the specified filter is null
     * @throws UnsupportedOperationException if elements cannot be removed
     *         from this collection.  Implementations may throw this exception if a
     *         matching element cannot be removed or if, in general, removal is not
     *         supported.
     * @since 1.8
     */
    default boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator<E> each = iterator();
        while (each.hasNext()) {
            if (filter.test(each.next())) {
                each.remove();
                removed = true;
            }
        }
        return removed;
    }

    /**
     * Retains only the elements in this collection that are contained in the
     * specified collection (optional operation).  In other words, removes from
     * this collection all of its elements that are not contained in the
     * specified collection.
     * 仅保留此集合中包含在指定集合中的元素(可选操作)。
     * 换句话说,从该集合中删除指定集合中不包含的所有元素。
     * 
     *
     * @param c collection containing elements to be retained in this collection 包含要保留在此集合中的元素的集合
     * @return <tt>true</tt> if this collection changed as a result of the call 如果此集合因调用而更改,则为true
     * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
     *         is not supported by this collection
     * @throws ClassCastException if the types of one or more elements
     *         in this collection are incompatible with the specified
     *         collection
     *         (<a href="#optional-restrictions">optional</a>)
     * @throws NullPointerException if this collection contains one or more
     *         null elements and the specified collection does not permit null
     *         elements
     *         (<a href="#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see #remove(Object)
     * @see #contains(Object)
     */
    boolean retainAll(Collection<?> c);

    /**
     * Removes all of the elements from this collection (optional operation).
     * The collection will be empty after this method returns.
     * 从此集合中删除所有元素(可选操作)。此方法返回后,集合将为空。
     * 
     * @throws UnsupportedOperationException if the <tt>clear</tt> operation
     *         is not supported by this collection
     */
    void clear();


    // Comparison and hashing 比较和hash操作

    /**
     * Compares the specified object with this collection for equality. <p>
     * 比较指定对象与此集合是否相等
     *
     * While the <tt>Collection</tt> interface adds no stipulations to the
     * general contract for the <tt>Object.equals</tt>, programmers who
     * implement the <tt>Collection</tt> interface "directly" (in other words,
     * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
     * or a <tt>List</tt>) must exercise care if they choose to override the
     * <tt>Object.equals</tt>.  It is not necessary to do so, and the simplest
     * course of action is to rely on <tt>Object</tt>'s implementation, but
     * the implementor may wish to implement a "value comparison" in place of
     * the default "reference comparison."  (The <tt>List</tt> and
     * <tt>Set</tt> interfaces mandate such value comparisons.)<p>
     * 虽然集合接口没有为Object.equals的一般约定添加任何规定,
     * 但“直接”实现集合接口的程序员(换句话说,创建一个属于集合但不是集合或列表的类)
     * 在选择重写Object.equals时必须小心。
     * 没有必要这样做,最简单的做法是依赖对象的实现,
     * 但实现者可能希望实现“值比较”来代替默认的“引用比较”。(列表和集合接口要求进行此类值比较。)
     * 
     * (默认的Object.equals实现是引用比较)
     * 
     * 
     * 
     * The general contract for the <tt>Object.equals</tt> method states that
     * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and
     * only if <tt>b.equals(a)</tt>).  The contracts for <tt>List.equals</tt>
     * and <tt>Set.equals</tt> state that lists are only equal to other lists,
     * and sets to other sets.  Thus, a custom <tt>equals</tt> method for a
     * collection class that implements neither the <tt>List</tt> nor
     * <tt>Set</tt> interface must return <tt>false</tt> when this collection
     * is compared to any list or set.  (By the same logic, it is not possible
     * to write a class that correctly implements both the <tt>Set</tt> and
     * <tt>List</tt> interfaces.)
     * Object.equals方法的一般约定规定equals必须是对称的(换句话说,a.equals(b)
     * 同时b.equals(a))。
     * List.equals和Set.equals的约定表示列表仅与其他列表相等,
     * 而集合则与其他集合相等。因此,当将此集合与任何列表或集合进行比较时,
     * 既不实现List接口也不实现Set接口的集合类的自定义equals方法必须返回false。
     * (根据相同的逻辑,不可能编写同时正确实现Set和List接口的类。)
     * 
     * 
     * 
     * 
     *
     * @param o object to be compared for equality with this collection 要与此集合进行相等性比较的对象
     * @return <tt>true</tt> if the specified object is equal to this
     * collection 如果指定的对象等于此集合,则为true
     *
     * @see Object#equals(Object)
     * @see Set#equals(Object)
     * @see List#equals(Object)
     */
    boolean equals(Object o);

    /**
     * Returns the hash code value for this collection.  While the
     * <tt>Collection</tt> interface adds no stipulations to the general
     * contract for the <tt>Object.hashCode</tt> method, programmers should
     * take note that any class that overrides the <tt>Object.equals</tt>
     * method must also override the <tt>Object.hashCode</tt> method in order
     * to satisfy the general contract for the <tt>Object.hashCode</tt> method.
     * In particular, <tt>c1.equals(c2)</tt> implies that
     * <tt>c1.hashCode()==c2.hashCode()</tt>.
     * 返回此集合的哈希代码值。虽然集合接口没有为Object.hashCode方法的通用约定添加任何规定,
     * 但程序员应该注意,任何重写Object.equals方法的类也必须重写Object.hashCode方法,
     * 以满足Object.hashCode方法的通用约定。
     * 特别是,c1.equals(c2)表示c1.hashCode()==c2.hashCode()。
     * 
     * 
     *
     * @return the hash code value for this collection 此集合的哈希代码值
     *
     * @see Object#hashCode()
     * @see Object#equals(Object)
     */
    int hashCode();

    /**
     * Creates a {@link Spliterator} over the elements in this collection.
     * 在此集合中的元素上创建Spliterator。
     * 
     * 
     *
     * Implementations should document characteristic values reported by the
     * spliterator.  Such characteristic values are not required to be reported
     * if the spliterator reports {@link Spliterator#SIZED} and this collection
     * contains no elements.
     * 实现应该记录拆分器报告的特征值。
     * 如果拆分器报告spliterator.size(),并且此集合不包含任何元素,
     * 则不需要报告此类特征值。
     * 
     * 
     *
     * <p>The default implementation should be overridden by subclasses that
     * can return a more efficient spliterator.  In order to
     * preserve expected laziness behavior for the {@link #stream()} and
     * {@link #parallelStream()}} methods, spliterators should either have the
     * characteristic of {@code IMMUTABLE} or {@code CONCURRENT}, or be
     * <em><a href="Spliterator.html#binding">late-binding</a></em>.
     * If none of these is practical, the overriding class should describe the
     * spliterator's documented policy of binding and structural interference,
     * and should override the {@link #stream()} and {@link #parallelStream()}
     * methods to create streams using a {@code Supplier} of the spliterator,
     * as in:
     * 默认实现应该被可以返回更高效的拆分器的子类覆盖。
     * 为了保持stream()和parallelStream()方法的预期惰性行为,
     * 拆分器应该具有IMMUTABLE或CONCURRENT的特性,或者是后期绑定。
     * 如果这些都不实用,则重写类应该描述拆分器的绑定和结构干扰的文档化策略,
     * 并且应该重写stream()和parallelStream()方法,以使用拆分器的Supplier创建流,如所示:
     * 
     * 
     * <pre>{@code
     *     Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics)
     * }</pre>
     * <p>These requirements ensure that streams produced by the
     * {@link #stream()} and {@link #parallelStream()} methods will reflect the
     * contents of the collection as of initiation of the terminal stream
     * operation. 
     * 这些要求确保stream()}和parallelStream()方法生成的流将反映终端流操作启动时收集的内容。
     *
     * @implSpec
     * The default implementation creates a
     * <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
     * from the collections's {@code Iterator}.  The spliterator inherits the
     * <em>fail-fast</em> properties of the collection's iterator.
     * 默认实现从集合的Iterator创建后期绑定spliterator。spliterator继承集合迭代器的fail fast属性。
     * 
     * 
     * <p>
     * The created {@code Spliterator} reports {@link Spliterator#SIZED}.
     * 创建的Spliterator报告Spliterator.SIZED
     *
     * @implNote
     * The created {@code Spliterator} additionally reports 创建的Spliterator加上报告
     * {@link Spliterator#SUBSIZED}.
     *
     * <p>If a spliterator covers no elements then the reporting of additional
     * characteristic values, beyond that of {@code SIZED} and {@code SUBSIZED},
     * does not aid clients to control, specialize or simplify computation.
     * However, this does enable shared use of an immutable and empty
     * spliterator instance (see {@link Spliterators#emptySpliterator()}) for
     * empty collections, and enables clients to determine if such a spliterator
     * covers no elements.
     * 如果拆分器不包含任何元素,则除了size和SUBSIZED
     * 之外的其他特征值的报告不会帮助客户端控制、专门化或简化计算。
     * 但是,这确实允许为空集合共享不可变的空拆分器实例
     * (请参见Spliterators.emptySpliterator()),
     * 并允许客户端确定此类拆分器是否不包含任何元素。
     * 
     * 
     *
     * @return a {@code Spliterator} over the elements in this collection
     * @since 1.8
     */
    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, 0);
    }

    /**
     * Returns a sequential {@code Stream} with this collection as its source.
     * 返回一个序列Stream,该集合作为其源。
     *
     * <p>This method should be overridden when the {@link #spliterator()}
     * method cannot return a spliterator that is {@code IMMUTABLE},
     * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
     * for details.)
     * 当spliterator() 方法无法返回 IMMUTABLE、
     * CONCURRENT或后期绑定的拆分器时,应重写此方法。
     * (有关详细信息,请参见spliterator())
     *
     * @implSpec
     * The default implementation creates a sequential {@code Stream} from the
     * collection's {@code Spliterator}.
     * 默认实现从集合的Spliterator创建序列Stream。
     * 
     *
     * @return a sequential {@code Stream} over the elements in this collection
     * @since 1.8
     */
    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    /**
     * Returns a possibly parallel {@code Stream} with this collection as its
     * source.  It is allowable for this method to return a sequential stream.
     * 返回一个可能与此集合并行的Stream作为其源。此方法允许返回顺序流。
     * 
     * 
     * <p>This method should be overridden when the {@link #spliterator()}
     * method cannot return a spliterator that is {@code IMMUTABLE},
     * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
     * for details.)
     * 当spliterator()方法无法返回IMMUTABLE、
     * CONCURRENT或后期绑定的拆分器时,应重写此方法。
     * (有关详细信息,请参见spliterator()))。
     * 
     *
     * @implSpec
     * The default implementation creates a parallel {@code Stream} from the
     * collection's {@code Spliterator}.
     * 默认实现从集合的Spliterator创建一个并行Stream。
     *
     * @return a possibly parallel {@code Stream} over the elements in this
     * collection 此集合中元素上可能存在的并行Stream
     * @since 1.8
     */
    default Stream<E> parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lolxxs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值