Java Collections Framework学习笔记之Collection接口

Java Collections Framework学习笔记之Collection接口

文章中使用的图均源: http://www.codejava.net

我们来一步步学习Collection的源码

从图中可以看出Collection接口继承了Iteratable接口,在介绍Collection之前,我们需要先了解一下Iteratable接口,而实现Iteratable接口的集合必须提供一个方法,这个方法返回一个Iterator类型的对象。

java.util.Iterator
  • Iterator接口的作用是:通过iterator方法,每个集合均可创建并返回给客户一个实现Iterator接口的对象,并将当前位置的概念在对象内部存储下来。
public interface Iterator<E> {

    boolean hasNext();

    E next();

    /**
     * Removes from the underlying collection the last element returned
     * by this iterator (optional operation).
     从底层集合移除通过迭代器返回的最后一个元素
     * This method can be called
     * only once per call to {@link #next}.  The behavior of an iterator
     * is unspecified if the underlying collection is modified while the
     * iteration is in progress in any way other than by calling this
     * method.
     这个方法只能在每次调用next时被调用。如果用除此方法以外的方式在迭代时修改底层集合,那么迭代器的行为将是未知的。

     意思就是,可以删除由next最新返回的项(此后不能再调用remove,除非你再调用next)
     */

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    /**
     * Performs the given action for each remaining element until all elements
     * have been processed or the action throws an exception.  Actions are
     * performed in the order of iteration, if that order is specified.
     * Exceptions thrown by the action are relayed to the caller.
     对每个剩余的元素执行给定的操作,直到处理完所有元素或操作抛出异常。
     如果指定了顺序,则按迭代顺序执行。这个操作抛出的异常会转给调用者。
     *
     * @since 1.8
     */
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}
  • 需要注意的是,在直接使用Iterator(不是通过增强for循环间接使用)时,要记住一个基本法则:如果对正在被迭代的集合进行结构上的改变(如add、remove、clear),那么迭代器就不再合法(会抛出ConcurrentModificationException)。这个我们会在后面介绍
java.lang.Iterable

Implementing this interface allows an object to be the target of the “for-each loop” statement.
实现这个接口使得对象可以成为“for-each 循环”语句的目标。

即实现Iterable接口的类可以拥有增强for循环

public interface Iterable<T>
//定义一个Iterator类型的方法,返回一个Iterator类型的对象。
    Iterator<T> iterator();

    /**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     对每个Iterable的元素执行给定操作,直到所有元素都处理完或操作抛出异常。除非实现类另有规定,否则按迭代顺序执行操作(如果指定了迭代顺序)。
     *
     * @since 1.8
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

    default Spliterator<T> spliterator() {
        return Spliterators.spliteratorUnknownSize(iterator(), 0);
    }

接下来进入到Collection中

java.util.Collection

要点:
- 抽象了集合的概念,存储一组类型相同的对象
- 继承了Iterable接口,可以拥有增强的for循环
- 注意该类的remove方法需要先查找到被删除的项然后移除(需要耗费查找的时间)

public interface Collection<E> extends Iterable<E> {
    // Query Operations

    int size();

    boolean isEmpty();

    boolean contains(Object o);

    Iterator<E> iterator();

    Object[] toArray();

    <T> T[] toArray(T[] a);

    // Modification Operations

    boolean add(E e);

    boolean remove(Object o);

    // Bulk Operations

    boolean containsAll(Collection<?> c);

    boolean addAll(Collection<? extends E> c);

    boolean removeAll(Collection<?> c);

    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;
    }

    boolean retainAll(Collection<?> c);

    void clear();


    // Comparison and hashing

    boolean equals(Object o);

    int hashCode();

    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, 0);
    }


    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }


    default Stream<E> parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
}

总的来说,Collection 是最基本的集合接口,一个 Collection 代表一组 Object,即 Collection 的元素, Java不提供直接继承自Collection的类,只提供继承于其的子接口(如List和set)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值