1. 程式人生 > >JDK源碼閱讀之Collection

JDK源碼閱讀之Collection

強制 more warnings end trees supported 參數類型 asm []

集合 Collection,根據已知的內容可以知道有List、Set、Map(嚴格說,Map不屬於Collection)等大類。

先查看 Collection,

public interface Collection<E> extends Iterable<E>

JDK說明如下:

/**
 * The root interface in the <i>collection hierarchy</i>.  A collection
 * represents a group of objects, known as its <i>elements</i>.  Some
 * collections allow duplicate elements and others do not.  Some are ordered
 * and others unordered.  The JDK does not provide any <i>direct</i>
 * implementations of this interface: it provides implementations of more
 * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>.  This interface
 * is typically used to pass collections around and manipulate them where
 * maximum generality is desired.
 *
 * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
 * duplicate elements) should implement this interface directly.
 *
 * <p>All general-purpose <tt>Collection</tt> implementation classes (which
 * typically implement <tt>Collection</tt> indirectly through one of its
 * subinterfaces) should provide two "standard" constructors: a void (no
 * arguments) constructor, which creates an empty collection, and a
 * constructor with a single argument of type <tt>Collection</tt>, which
 * creates a new collection with the same elements as its argument.  In
 * effect, the latter constructor allows the user to copy any collection,
 * producing an equivalent collection of the desired implementation type.
 * There is no way to enforce this convention (as interfaces cannot contain
 * constructors) but all of the general-purpose <tt>Collection</tt>
 * implementations in the Java platform libraries comply.
 *
 * <p>The "destructive" methods contained in this interface, that is, the
 * methods that modify the collection on which they operate, are specified to
 * throw <tt>UnsupportedOperationException</tt> if this collection does not
 * support the operation.  If this is the case, these methods may, but are not
 * required to, throw an <tt>UnsupportedOperationException</tt> if the
 * invocation would have no effect on the collection.  For example, invoking
 * the {
@link #addAll(Collection)} method on an unmodifiable collection may, * but is not required to, throw the exception if the collection to be added * is empty. * * <p><a name="optional-restrictions"/> * Some collection implementations have restrictions on the elements that * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting * to query the presence of an ineligible element may throw an exception, * or it may simply return false; some implementations will exhibit the former * behavior and some will exhibit the latter. More generally, attempting an * operation on an ineligible element whose completion would not result in * the insertion of an ineligible element into the collection may throw an * exception or it may succeed, at the option of the implementation. * Such exceptions are marked as "optional" in the specification for this * interface. * * <p>It is up to each collection to determine its own synchronization * policy. In the absence of a stronger guarantee by the * implementation, undefined behavior may result from the invocation * of any method on a collection that is being mutated by another * thread; this includes direct invocations, passing the collection to * a method that might perform invocations, and using an existing * iterator to examine the collection. * * <p>Many methods in Collections Framework interfaces are defined in * terms of the {
@link Object#equals(Object) equals} method. For example, * the specification for the {@link #contains(Object) contains(Object o)} * method says: "returns <tt>true</tt> if and only if this collection * contains at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt> * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be * invoked for any element <tt>e</tt>. Implementations are free to implement * optimizations whereby the <tt>equals</tt> invocation is avoided, for * example, by first comparing the hash codes of the two elements. (The * {
@link Object#hashCode()} specification guarantees that two objects with * unequal hash codes cannot be equal.) More generally, implementations of * the various Collections Framework interfaces are free to take advantage of * the specified behavior of underlying {@link Object} methods wherever the * implementor deems it appropriate. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <E> the type of elements in this collection * * @author Josh Bloch * @author Neal Gafter * @see Set * @see List * @see Map * @see SortedSet * @see SortedMap * @see HashSet * @see TreeSet * @see ArrayList * @see LinkedList * @see Vector * @see Collections * @see Arrays * @see AbstractCollection * @since 1.2 */

大意是:

Collection接口是集合框架的根接口。JDK沒有為該接口提供任何直接實現,而是提供了更細化的子接口的實現,如Set、List。

所有通用目的的實現類應該提供兩個標準構造方法:一個空參數的構造器、一個單參數且參數類型為Collection的構造器。沒有強制措施,純屬自覺,JDK很自覺。

每個實現類的同步策略由自己決定。

集合框架接口的很多方法都是基於equals方法,例如contains(obj)。

不過,先不急於深入Collection接口,先看看其繼承的Iterable接口,該接口只有一個方法:

public interface Iterable<T> {
    Iterator<T> iterator();
}

繼續展開 Iterator,還是一個接口:

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();
}

如果使用過該接口,應該明白前兩個方法的意義,一個用於判斷是否還有下一個元素,另一個用於獲取下一個元素同時移動遊標。最後一個方法其實是刪除當前指向的元素,屬於可選的待實現接口方法。

事實上,該接口,Iterator取代了原有的Enumeration接口,對比一下就明白了:

public interface Enumeration<E> {
    boolean hasMoreElements();
    E nextElement();
}

Iterator 和 Enumeration 如出一轍,只不過 Iterator 更簡潔,且多了一個操作。

再返回來看看 Iterable 接口,其唯一的方法是 iterator(),要求返回一個 Iterator對象;所以 Collection 接口的實現們必然實現該方法,來測試一下:

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testIterator() {
    Collection collection = null;
    collection = new ArrayList();
    collection.add(1);
    collection.add(2);
    collection.add(3);

    Iterator iterator = collection.iterator(); // Iterator
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

OK,現在來看看Collection本身的接口:

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);
    boolean retainAll(Collection<?> c);
    void clear();


    // Comparison and hashing  - 對比和哈希
    boolean equals(Object o);
    int hashCode();
}

JDK源碼閱讀之Collection