三、详解集合之Collection

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> {
    // Query Operations 查询操作

    //集合大小
    int size();

    //集合是否为空
    boolean isEmpty();

    //集合中是否存在指定元素
    boolean contains(Object o);

    //获取迭代器
    Iterator iterator();

    //将集合转换为数组
    Object[] toArray();

    //将集合转换为指定类型数组
     T[] toArray(T[] a);

    // Modification Operations 修改操作

    //添加元素
    boolean add(E e);

    //移除元素
    boolean remove(Object o);

    // Bulk Operations 整体操作

    //判断集合中是否包含指定集合中的所有元素
    boolean containsAll(Collection c);

    //向集合中添加指定集合的所有元素
    boolean addAll(Collection c);

    //移除集合中和c集合中相同的元素
    boolean removeAll(Collection c);

    //移除集合中符合条件的元素
    default boolean removeIf(Predicatesuper E> filter) {
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator each = iterator();
        while (each.hasNext()) {
            if (filter.test(each.next())) {
                each.remove();
                removed = true;
            }
        }
        return removed;
    }

    //集合与c取交集,保留两集合共同元素
    boolean retainAll(Collection c);

    //清空集合
    void clear();

    // Comparison and hashing 比较和hash

    //重写比较方法
    boolean equals(Object o);

    //重写hashCode方法
    int hashCode();

    //可分割迭代器
    @Override
    default Spliterator spliterator() {
        return Spliterators.spliterator(this, 0);
    }

    //获取流
    default Stream stream() {
        return StreamSupport.stream(spliterator(), false);
    }

    //获取并行流
    default Stream parallelStream() {
        return StreamSupport.stream(spliterator(), true);
    }
}

详解:

  1. Collection接口是java集合的父接口,由此引出了java的List,Set等
  2. Collection接口主要定义了查询、修改、整体、重写比较和hash等操作
  3. 查询操作包括了:集合大小,是否为空,是否存在指定元素,获取迭代器,转换数组
  4. 修改操作包括了:添加,删除
  5. 整体操作包括了:两个集合取交集,添加,删除,清空集合等
  6. 比较和hash包括了:重写equals和hashCode方法
  7. 移除集合中符合条件的元素的removeIf()方法中,通过获取Iterator对集合进行遍历,test()筛选,如果符合条件,调用remove方法移除

你可能感兴趣的:(java)