文章中使用的图均源: http://www.codejava.net
从图中可以看出Collection接口继承了Iteratable接口,在介绍Collection之前,我们需要先了解一下Iteratable接口,而实现Iteratable接口的集合必须提供一个方法,这个方法返回一个Iterator类型的对象。
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中
要点: - 抽象了集合的概念,存储一组类型相同的对象 - 继承了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)。
