Java源码——Collection接口学习记录


Collection的继承实现关系类图

public interface Collection<E> extends Iterable<E>

Collection 的意思是集合,它是Java集合类的顶级接口之一。它继承了Iterable接口,也就是说,它的实现类也可以实现迭代功能。Colection接口统一定义了一套简单集合具备的功能接口。也就是说实现这个接口就可以创建一个自己的集合类。

该接口中的参数< E >:
the type of elements in this collection.
集合中所含有的元素的类型。

Collection接口中的方法列表:

方法说明
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator iterator();覆盖Iterable的方法
Object[] toArray();
< T > T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
default boolean removeIf(Predicate<? super E> filter)Jdk8 新增
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
default Spliterator spliterator()覆盖Iterable的方法
default Stream stream()Jdk8 新增
default Stream parallelStream()Jdk8 新增
default void forEach(Consumer<? super T> action)(源码中没有它的声明)继承自Iterable接口

这些方法可以分个类:

  1. 增加:(add/addAll)
  2. 删除 (remove/removeAll/clear/retainAll)
  3. 查询(contain/containAll/iterator/size/isEmpty)
  4. 转数组(toArray/toArray(T[]))

还有一个用于遍历的函数 forEach 。因为 forEach 方法在Iterable接口中已经写了方法体,所有直接继承来就能用,也不用重写。

那为什么要重写iterator()方法和spliterator()方法呢?它们原本不就是抽象方法吗,直接继承过来使用不可以吗?这个问题在下面方法详述中解释。

JDK8 在Collection接口中新增了几个方法:

  1. removeIf(Predicate<? super E> filter)
    使用lambda方式移除元素
  2. Spliterator spliterator()
    这个在Iterable接口中见过了,返回并发分割器,用于并发流式处理的时候调用
  3. Stream stream()
    返回流对象
  4. Stream parallelStream()
    返回并发流式对象

重点方法详述

接口中的多数方法都是抽线方法,这里记录了一下比较重要的方法,包括jdk8的型特性。

iterator()方法

/**
 * 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();

通过看注释其实就能大概明白Java设计人员的思路,其实Iterable接口可以看成从很多容器类提取出来的共同特性,把这些特性作为一个接口。但是对于不同的容器累,这个共有特性的具体实现细节是不同的。所以就要自己定义自己系列的迭代器规则,并让其所有实现类都遵循这个规则。个人觉得,Collection作为集合类容器的顶级接口,把它显示的写出来,就是提示容器类,要定义自己的迭代器规则。(感觉如果不显示的覆盖应该也没有大问题吧。。。个人理解,如果有理解的不对的地方希望有大佬可以指教一二)

Collection新增特性:

removeIf(Predicate<? super E> filter)方法
    /**
     * 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;
    }

使用lambda方式移除元素

Stream stream()方法
    /**
     * Returns a sequential {@code Stream} with this collection as its source.
     *
     * <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.)
     *
     * @implSpec
     * The default implementation creates a sequential {@code Stream} from the
     * collection's {@code Spliterator}.
     *
     * @return a sequential {@code Stream} over the elements in this collection
     * @since 1.8
     */
    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

返回流对象

Stream parallelStream()方法
    /**
     * Returns a possibly parallel {@code Stream} with this collection as its
     * source.  It is allowable for this method to return a sequential 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.)
     *
     * @implSpec
     * The default implementation creates a parallel {@code Stream} from the
     * collection's {@code Spliterator}.
     *
     * @return a possibly parallel {@code Stream} over the elements in this
     * collection
     * @since 1.8
     */
    default Stream<E> parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }

返回并发流式对象

官方介绍:

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.Bags or multisets (unordered collections that may contain duplicate elements) should implement this interface directly.

All general-purpose Collection implementation classes (which typically implement Collection 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 Collection, 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 Collection implementations in the Java platform libraries comply.

The “destructive” methods contained in this interface, that is, the methods that modify the collection on which they operate, are specified to throw UnsupportedOperationException if this collection does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the collection. For example, invoking the addAll(Collection) method on an unmodifiable collection may, but is not required to, throw the exception if the collection to be added is empty.

Some collection implementations have restrictions on the elements that they may contain. 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 NullPointerException or ClassCastException. 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.

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.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object o) method says: “returns true if and only if this collection contains at least one element e such that (o == null ? e==null : o.equals(e)).” This specification should not be construed to imply that invoking Collection.contains with a non-null argument o will cause o.equals(e) to be invoked for any element e. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two elements. (The 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 Object methods wherever the implementor deems it appropriate.

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 clone(), equals(), hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.

This interface is a member of the Java Collections Framework.

集合框架全景图:
jdk8集合框架全景继承实现树

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值