Java集合-基於JDK11(1)

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章