前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java.util.Collection[源码解读(下)]

java.util.Collection[源码解读(下)]

作者头像
小诸葛
发布2020-04-14 15:55:05
4430
发布2020-04-14 15:55:05
举报
文章被收录于专栏:方法论方法论

前言

上篇文章介绍了Collection接口的用途,本篇文章来介绍Collection接口的方法。

查询操作

1.size()

方法返回集合中元素的数量,如果元素的数量超过Integer.MAX_VALUE(即2147483647)个,则返回Integer.MAX_VALUE。

代码语言:javascript
复制
/**
     * 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>.
     *
     * @return the number of elements in this collection
     */
    int size();

2.contains(Object o)

如果集合包含指定的元素,返回true。更正式而言:当且仅当集合包含至少一个符合以下条件的元素e时返回true:

(o==null ? e == null : o.equals(e))

代码语言:javascript
复制
/**
     * 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>.
     *
     * @param o element whose presence in this collection is to be tested
     * @return <tt>true</tt> if this collection contains the specified
     *         element
     * @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>)
     */
    boolean contains(Object o);

3.iterator()

返回一个包含集合中所有元素的迭代器。但是并不对元素的顺序做保证(除非这个集合是一个提供顺序保证的类的实例)。

代码语言:javascript
复制
/**
     * 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();

4.toArray()

返回一个包含集合所有元素的Object数组,如果这个集合保证了它的迭代器返回元素的顺序,那么此方法返回的元素的顺序必须也是同样的顺序。

这个方法返回的数组将会是安全的,因为这个集合中没有任何指向这个数组的引用。换句话说,这个方法必须分配一个新的数组来保存集合的元素,即使这个集合本身就是数组类型的。

这个方法充当基于数组和基于集合的api之间的桥梁。

代码语言:javascript
复制
/**
     * 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.
     *
     * @return an array containing all of the elements in this collection
     */
    Object[] toArray();

5.toArray(T[] a)

返回一个包含集合所有元素的数组,被返回的数组的类型和参数中指定的类型是一致的。如果集合的长度适合指定的数组(即指定的数组可以容纳完集合的所有元素,或者说指定的数组的长度不小于集合的长度),将集合中的对象拷贝到指定的数组中,然后返回该数组,否则(即指定的数组的长度小于集合的长度),返回一个包含所有集合元素的新数组,新数组的类型和参数数组的类型一致,数组长度和集合大小一致。

如果集合的元素全部放入数组中后,数组还有空余的空间(即集合的长度小于数组的长度),则紧跟数组最后一个元素的数组项将被赋为null(仅在调用者知道集合中不含null元素的情况下获取集合长度的时候很有用)。

如果这个集合保证了它的迭代器返回元素的顺序,那么此方法返回的元素的顺序必须也是同样的顺序。

类似toArray()方法,此方法充当基于数组和基于集合的api之间的桥梁。进一步说,这个方法允许精确控制返回数组的运行时类型,并且在某些特定的情况下(即指定数组的长度不小于集合的长度的时候),用来节省内存分配开销。

假定x是一个仅包含String类型元素的集合,下面的代码可以将集合的元素拷贝到一个新的数组中当中去

代码语言:javascript
复制
String[] y = x.toArray(new String[0]);

需要注意的是toArray(new Object[0])和toArray()产生的效果是一模一样的

代码语言:javascript
复制
/**
     * 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.)
     *
     * <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.
     *
     * <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>:
     *
     * <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>.
     *
     * @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.
     * @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);

修改操作

6.add(E e)

此方法可以确保集合包含指定的元素(可选操作),如果集合发生了改变,返回true(即指定的元素成功添加进了集合中),如果此集合不允许包含重复元素并已包含了此元素,返回false。

一些支持此方法的实现类可能会对添加进此集合中的元素设置限制.特别是一些集合不允许添加null元素,还有一些会强制限制被添加的元素的类型.实现此接口的类应该明确的详细说明任何对于被添加的元素的限制条件。

如果一个集合拒绝添加一个特定的元素,而不是因为它已经包含了此元素,此时必须抛出一个异常(而不是返回false),这保证了集合在调用返回后始终包含指定元素。

代码语言:javascript
复制
/**
     * 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>
     *
     * 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>
     *
     * 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.
     *
     * @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
     * @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
     * @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);

7.remove(Object o)

从集合中移除指定的实例(如果集合中存在这个实例)。更正式的讲,从集合中移除符合以下条件的一个或多个元素e

(o==null)?e==null:o.equals(e)

如果此集合包含指定的元素(或者说此方法被调用后集合改变了),返回true,否则返回false。

代码语言:javascript
复制
/**
     * 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).
     *
     * @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
     * @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);

批量处理

8.containsAll(Collection<?> c)

如果集合中包含指定的集合中的所有元素,返回true,否则,返回false。

代码语言:javascript
复制
/**
     * Returns <tt>true</tt> if this collection contains all of the elements
     * in the specified collection.
     *
     * @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
     * @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);

9.addAll(Collection<? extends E> c)

将指定集合中的所有元素添加到此集合中。如果在添加过程中,指定的集合中被修改了(添加或删除),则此添加操作产生的行为是无法预知的(这意味着如果指定的集合是此集合,而此集合是非空的,则此次添加行为是未定义的)。

代码语言:javascript
复制
/**
     * 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.)
     *
     * @param c collection containing elements to be added to this collection
     * @return <tt>true</tt> if this collection changed as a result of the call
     * @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);

10.removeAll(Collection<?> c)

从此集合中移除包含在指定集合中的所有元素,在此方法被调用后,这个集合将不再包含任何在指定集合中包含的元素。

代码语言:javascript
复制
/**
     * 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
     * @return <tt>true</tt> if this collection changed as a result of the
     *         call
     * @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);

11.default boolean removeIf(Predicate<? super E> filter)

移除此集合中符合指定断言的所有元素。

代码语言:javascript
复制
/**
     * 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.
     *
     * @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.
     *
     * @param filter a predicate which returns {@code true} for elements to be
     *        removed
     * @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;
    }

12.retainAll(Collection<?> c)

保留此集合中同时也包含在指定集合中的所有元素,换句话说,移除此集合中没有包含在指定集合中的所有元素。

代码语言:javascript
复制
/**
     * 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
     * @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);

13.clear()

移除此集合中的所有元素,当调用此方法后,此集合将成为空的集合。

代码语言:javascript
复制
/**
     * 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();

比较和hash

14.equals(Object o)

比较此集合和指定的元素是否相等

由于此集合没有为equals方法规定任何通用协议,直接实现此接口(换句话说,创建一个集合类,而此集合类不是set也不是list)的程序员如果选择覆写equals方法必须额外小心。其实没有必要一定要覆写equals方法,依赖Object的equals方法是最不需要担心的,但是继承者如果希望实现一个比较集合中元素值而不是默认的比较对象地址的方法,则需要覆写equals方法。List和Set的equals方法就是比较集合中值的方法。

Object中的equals方法中有着这样常规的规定:equals必须是对称的(换句话说,当且仅当b.equals(a)时a.equals(b))。List和Set中的equals方法这样规定:List仅和其他的List类型的对象相等,而Set也仅和其他Set类型的对象相等。也就是说当任何List和Set进行比较时,直接返回false,反之亦然(同理,想要编写一个同时实现list和set的类是不可能的)。

代码语言:javascript
复制
/**
     * 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>
     *
     * 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.)
     *
     * @param o object to be compared for equality with this collection
     * @return <tt>true</tt> if the specified object is equal to this
     * collection
     *
     * @see Object#equals(Object)
     * @see Set#equals(Object)
     * @see List#equals(Object)
     */
    boolean equals(Object o);

15.hashCode

返回集合的哈希码。由于此接口没有为Object的hashCode方法制定任何一般的协议,程序员需要注意任何类覆写equals方法时必须覆写hashCode方法来满足hashCode的通用协定。特别地,如果c1.equals(c2),那么c1.hashCode()==c2.hashCode。

代码语言:javascript
复制
/**
     * 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>.
     *
     * @return the hash code value for this collection
     *
     * @see Object#hashCode()
     * @see Object#equals(Object)
     */
    int hashCode();
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小诸葛的博客 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档