Java集合体系一览图(UML)
1.Iterable 接口
Iterable,即迭代器的意思。其作用是为集合类提供for-each循环遍历的支持,只要让一个类实现这个接口,该类的对象就可以成为for-each循环遍历的目标。换句话说,想让一个Java对象支持for-each遍历,只要让它的类实现Iterable接口即可。而这具体又是如何做到的呢?我们来看下它的源码。
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
* 返回建立在类型为T的元素之上的一个Iterator对象
* @return an Iterator.
此方法是Iterable接口的主要方法。我们知道,想让一个类实现Iterable接口,其对象就可以使
用for-each遍历。而具体如何做到就是通过此方法。比如说,我们可以通过 Iterator iterator
= strings.iterator(); 的方式取得集合的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. Actions are performed in the order of iteration, if that
* order is specified. Exceptions thrown by the action are relayed to the
* caller.
* <p>
* The behavior of this method is unspecified if the action performs
* side-effects that modify the underlying source of elements, unless an
* overriding class has specified a concurrent modification policy.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
将集合中的每个元素作为参数传递给action执行特定的操作,直到所有元素都被处理过或者某个元
素在被处理的过程中抛出异常。
执行顺序:除非实现类另有所指,否则各个元素被执行action操作时,会按照元素被迭代时的次序
执行。
异常抛出:元素被执行action操作时,如果抛出异常,异常将会被中继到方法的调用方。
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
/**
* Creates a {@link Spliterator} over the elements described by this
* {@code Iterable}.
*
* @implSpec
* The default implementation creates an
* <em><a href="../util/Spliterator.html#binding">early-binding</a></em>
* spliterator from the iterable's {@code Iterator}. The spliterator
* inherits the <em>fail-fast</em> properties of the iterable's iterator.
*
* @implNote
* The default implementation should usually be overridden. The
* spliterator returned by the default implementation has poor splitting
* capabilities, is unsized, and does not report any spliterator
* characteristics. Implementing classes can nearly always provide a
* better implementation.
*
* @return a {@code Spliterator} over the elements described by this
* {@code Iterable}.
* @since 1.8
创建一个作用在迭代器的元素之上的Spliterator。
*/
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
2.Iterator接口
public interface Iterator<E> {
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
*
* @return {@code true} if the iteration has more elements
判断一个对象集合是否还有下一个元素。
当迭代器中还有元素时,返回true。即,当如果再调用next()方法还可以返回一个元素,而不是抛
出异常时,返回true。
*/
boolean hasNext();
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration
* @throws NoSuchElementException if the iteration has no more elements
获取迭代器中的下一个元素
当迭代器中没有元素时,调用此方法会抛出NoSuchElementException异常。
*/
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}.
* <p>
* 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, unless an overriding class has specified a
* concurrent modification policy.
* <p>
* The behavior of an iterator is unspecified if this method is called
* after a call to the {@link #forEachRemaining forEachRemaining} method.
*
* @implSpec
* The default implementation throws an instance of
* {@link UnsupportedOperationException} and performs no other action.
*
* @throws UnsupportedOperationException if the {@code remove}
* operation is not supported by this iterator
*
* @throws IllegalStateException if the {@code next} method has not
* yet been called, or the {@code remove} method has already
* been called after the last call to the {@code next}
* method
删除最后一个元素
可以看到方法里面直接抛出异常,也就是默认是不支持删除操作的。为什么要这样做,是因为在很
多情况下执行删除操作其结果不可预测,比如,当执行删除操作时,数据集合正好被修改中
*/
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.
* <p>
* The behavior of an iterator is unspecified if the action modifies the
* collection in any way (even by calling the {@link #remove remove} method
* or other mutator methods of {@code Iterator} subtypes),
* unless an overriding class has specified a concurrent modification policy.
* <p>
* Subsequent behavior of an iterator is unspecified if the action throws an
* exception.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* while (hasNext())
* action.accept(next());
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
此方法主要是将迭代器中剩下的还没遍历到的每个元素都发给action来执行特定操作
*/
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
3.ListIterator接口
ListIterator既然是继承Iterator接口,所以自然就有Iterator的所有方法。我们只需要关注它在Iterator的基础上新增加的方法即可。不过,要注意到ListIterator重写了Iterator的remove()方法。
public interface ListIterator<E> extends Iterator<E> {
// Query Operations
/**
* Returns {@code true} if this list iterator has more elements when
* traversing the list in the forward direction. (In other words,
* returns {@code true} if {@link #next} would return an element rather
* than throwing an exception.)
*
* @return {@code true} if the list iterator has more elements when
* traversing the list in the forward direction
*/
boolean hasNext();
/**
* Returns the next element in the list and advances the cursor position.
* This method may be called repeatedly to iterate through the list,
* or intermixed with calls to {@link #previous} to go back and forth.
* (Note that alternating calls to {@code next} and {@code previous}
* will return the same element repeatedly.)
*
* @return the next element in the list
* @throws NoSuchElementException if the iteration has no next element
*/
E next();
/**
* Returns {@code true} if this list iterator has more elements when
* traversing the list in the reverse direction. (In other words,
* returns {@code true} if {@link #previous} would return an element
* rather than throwing an exception.)
*
* @return {@code true} if the list iterator has more elements when
* traversing the list in the reverse direction
判断逆向遍历时,前面是否还有元素未遍历
*/
boolean hasPrevious();
/**
* Returns the previous element in the list and moves the cursor
* position backwards. This method may be called repeatedly to
* iterate through the list backwards, or intermixed with calls to
* {@link #next} to go back and forth. (Note that alternating calls
* to {@code next} and {@code previous} will return the same
* element repeatedly.)
*
* @return the previous element in the list
* @throws NoSuchElementException if the iteration has no previous
* element
获取前一个元素
*/
E previous();
/**
* Returns the index of the element that would be returned by a
* subsequent call to {@link #next}. (Returns list size if the list
* iterator is at the end of the list.)
*
* @return the index of the element that would be returned by a
* subsequent call to {@code next}, or list size if the list
* iterator is at the end of the list
获取正向遍历时下一个元素的位置
如果到达列表的末端,就返回列表的大小
*/
int nextIndex();
/**
* Returns the index of the element that would be returned by a
* subsequent call to {@link #previous}. (Returns -1 if the list
* iterator is at the beginning of the list.)
*
* @return the index of the element that would be returned by a
* subsequent call to {@code previous}, or -1 if the list
* iterator is at the beginning of the list
获取逆向遍历时前一个元素的位置
如果到达列表大前端,就返回-1
*/
int previousIndex();
// Modification Operations
/**
* Removes from the list the last element that was returned by {@link
* #next} or {@link #previous} (optional operation). This call can
* only be made once per call to {@code next} or {@code previous}.
* It can be made only if {@link #add} has not been
* called after the last call to {@code next} or {@code previous}.
*
* @throws UnsupportedOperationException if the {@code remove}
* operation is not supported by this list iterator
* @throws IllegalStateException if neither {@code next} nor
* {@code previous} have been called, or {@code remove} or
* {@code add} have been called after the last call to
* {@code next} or {@code previous}
ListIterator的remove()方法不再是默认抛出一个异常,也就是说,实现ListIterator的集合默
认可以删除元素。
此方法可以删除next()或者previous()返回的元素(可选操作)
*/
void remove();
/**
* Replaces the last element returned by {@link #next} or
* {@link #previous} with the specified element (optional operation).
* This call can be made only if neither {@link #remove} nor {@link
* #add} have been called after the last call to {@code next} or
* {@code previous}.
*
* @param e the element with which to replace the last element returned by
* {@code next} or {@code previous}
* @throws UnsupportedOperationException if the {@code set} operation
* is not supported by this list iterator
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws IllegalArgumentException if some aspect of the specified
* element prevents it from being added to this list
* @throws IllegalStateException if neither {@code next} nor
* {@code previous} have been called, or {@code remove} or
* {@code add} have been called after the last call to
* {@code next} or {@code previous}
替换next()或者previous()返回的最后一个元素(可选操作),此方法只能在没有调用
remove()、add()方法时调用
*/
void set(E e);
/**
* Inserts the specified element into the list (optional operation).
* The element is inserted immediately before the element that
* would be returned by {@link #next}, if any, and after the element
* that would be returned by {@link #previous}, if any. (If the
* list contains no elements, the new element becomes the sole element
* on the list.) The new element is inserted before the implicit
* cursor: a subsequent call to {@code next} would be unaffected, and a
* subsequent call to {@code previous} would return the new element.
* (This call increases by one the value that would be returned by a
* call to {@code nextIndex} or {@code previousIndex}.)
*
* @param e the element to insert
* @throws UnsupportedOperationException if the {@code add} method is
* not supported by this list iterator
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws IllegalArgumentException if some aspect of this element
* prevents it from being added to this list
添加一个元素
将元素添加在next()返回的元素的前面,或者previous()返回的元素的后面(可选操作)
*/
void add(E e);
}
4.Collection源码
public interface Collection<E> extends Iterable<E> {
//返回集合的元素个数
int size();
//判断集合是否为空
boolean isEmpty();
// 如果这个集合至少包含一个指定的元素就返回true,
//如果指定的元素和集合中的元素不兼容,会抛出 ClassCastException
// 如果指定的元素为空并且该集合不允许元素为空时,会抛出 NullPointerException
boolean contains(Object o);
// 返回集合中元素的迭代器,它不保证元素的有序性 (除非该集合本身的实现可以保证元素的顺序)
Iterator<E> iterator();
// 返回一个包含集合中所有元素的数组,元素的顺序性和 iterator 一样,由集合实现类本身决定
// 这个方法返回的数组时安全的,因为集合不用保留对返回数组的引用,我们可以任意修改而不影响集合本身
Object[] toArray();
// 返回包含该集合中所有元素的数组,数组的运行时类型是指定数组的类型,
// 如果指定的数组适合集合的大小,直接返回其中,否则重新创建数组
<T> T[] toArray(T[] a);
//返回集合的所有元素
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
//往集合中添加一个元素,如果集合允许更改就返回true,如果集合不允许元素重复并且已经包含了此元素,则返回false
boolean add(E e);
//从集合中删除指定元素的单个实例 如果集合允许改变就返回true
boolean remove(Object o);
// 如果该集合包含指定集合的所有元素 则返回true
boolean containsAll(Collection<?> c);
// 添加指定集合的所有元素到该集合中
// 如果在添加操作的过程中修改了指定的集合 ,则此操作的行为是不确定的,不安全
boolean addAll(Collection<? extends E> c);
//在该集合中删除指定集合的所有元素,反方法成功返回后,该集合中将不再包含任何指定集合中的元素
boolean removeAll(Collection<?> c);
// 删除满足给定条件的所有元素,如果在迭代期间发生运行时异常,那么将返回给调用者
// 注意:这是JDK1.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;
}
// 从集合中删除不包含在指定集合中的所有元素
boolean retainAll(Collection<?> c);
// 清空集合中的所有元素,该方法返回后,集合将为空
void clear();
// 将指定的对象与集合进行比较
boolean equals(Object o);
// 返回在这个集合的hashCode值
int hashCode();
// 在此集合中的元素上创建Spliterator/
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
// 返回以此集合为源的顺序Stream。/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
// 以此集合作为源返回可能并行的Stream。 此方法允许返回顺序流。
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}