Collection接口详解

Collection接口

Collection接口做为集合类的父类接口,Collectio位于java.util包下,Collectio定义了不少集合操做的方法。今天我但愿经过对源码的查阅来对Collection接口有所认识,下面咱们直接进入源码分析:java

Collection接口源码

图片描述
能够看出,Collection接口继承Iterable接口。数组

Collection接口方法汇总以及详解

package java.util;

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

public interface Collection<E> extends Iterable<E> {
    /**
     * @return 用于返回集合中元素的个数(最大个数)
     */
    int size();

    /**
     * @return 用于判断集合中是否存在某个元素,不存在返回true
     */
    boolean isEmpty();

    /**
     * 判断集合中是否存在指定元素,存在返回true
     *
     * @param o是用于判断的元素
     */
    boolean contains(Object o);

    /**
     * @return 返回可用于遍历的迭代器
     */
    Iterator<E> iterator();

    /**
     * @return 将集合转变成数组
     */
    Object[] toArray();

    /**
     * @return 将指定集合转变成对应的数组
     */
    <T> T[] toArray(T[] a);


    /**
     * @return 往集合中添加元素,添加成功返回true
     */
    boolean add(E e);

    /**
     * @return 在集合中删除指定的元素,成功返回true
     */
    boolean remove(Object o);

    /**
     * @return 判断集合中是否包含集合C,若是包含返回true
     */
    boolean containsAll(Collection<?> c);

    /**
     * @return 将集合C添加到集合中,添加成功返回true
     */
    boolean addAll(Collection<? extends E> c);

    /**
     * @return 从集合中删除集合C,删除成功返回true
     */
    boolean removeAll(Collection<?> c);

    /**
     * @return 删除集合中复合条件的元素,删除成功返回true
     * @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;
    }

    /**
     * @return 保留集合中集合C中的元素
     */
    boolean retainAll(Collection<?> c);

    /**
     * 清空集合中的全部元素
     */
    void clear();

    /**
     * @return 比较O与集合中的元素
     */
    boolean equals(Object o);

    /**
     * @return 返回此集合的哈希码值。
     */
    int hashCode();

    /**
     *
     * @return a {@code Spliterator} over the elements in this collection
     * @since 1.8
     */
    @Override
    default Spliterator<E> spliterator() {
        return Spliterators.spliterator(this, 0);
    }

    /**
     * @return a sequential {@code Stream} over the elements in this collection
     * @since 1.8
     */
    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    /**
     * @return a possibly parallel {@code Stream} over the elements in this
     * collection
     * @since 1.8
     */
    default Stream<E> parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
}
相关文章
相关标签/搜索