首页 > 代码库 > java集合框架

java集合框架

什么是java集合框架呢?

            在java中,集合框架指的是用于盛放与操作集合的通用架构。在这里面,盛放指的是类似数组一样保存数据的功能,而操作则是有关集合的增删改查等操作操作。在集合框架中。主要包括了下面三个部分:
  • 接口(定义了一系列抽象的数据类型)
  • 实现(接口的详细实现类)
  • 算法(一些经常使用的计算。包括排序,搜索)

设计目标

  • 降低开发人员的工作量
  • 加快开发人员的开发速度以及加强代码的质量
  • 同意不相关接口之间的互操作性
  • 降低学习与应用新API
  • 降低设计新的API
  • 促进软件的复用

核心接口

        在集合框架中。系统定义了一系列核心接口,在经常使用操作中,主要包括了:Collection,List,Set,Map,Queue等。详细的例如以下图所看到的。
技术分享
            从图中能够看出。Collection作为最大的集合接口,Set,List,Queue,Deque继承Collection,Map则是一类新的接口。以下我们直接从源代码看看Collection的接口定义。Collection源代码例如以下:
public interface Collection<E> extends Iterable<E> {
    // Query Operations

    /**
     * Returns the number of elements in this collection.  If this collection
     * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of elements in this collection
     */
    int size();

    /**
     * Returns <tt>true</tt> if this collection contains no elements.
     *
     * @return <tt>true</tt> if this collection contains no elements
     */
    boolean isEmpty();

    /**
     * Returns <tt>true</tt> if this collection contains the specified element.
     * More formally, 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>. * * @param o element whose presence in this collection is to be tested * @return <tt>true</tt> if this collection contains the specified * element * @throws ClassCastException if the type of the specified element * is incompatible with this collection * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * collection does not permit null elements * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) */ boolean contains(Object o); /** * Returns an iterator over the elements in this collection. There are no * guarantees concerning the order in which the elements are returned * (unless this collection is an instance of some class that provides a * guarantee). * * @return an <tt>Iterator</tt> over the elements in this collection */ Iterator<E> iterator(); /** * Returns an array containing all of the elements in this collection. * If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements in * the same order. * * <p>The returned array will be "safe" in that no references to it are * maintained by this collection. (In other words, this method must * allocate a new array even if this collection is backed by an array). * The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this collection */ Object[] toArray(); /** * Returns an array containing all of the elements in this collection; * the runtime type of the returned array is that of the specified array. * If the collection fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this collection. * * <p>If this collection fits in the specified array with room to spare * (i.e., the array has more elements than this collection), the element * in the array immediately following the end of the collection is set to * <tt>null</tt>. (This is useful in determining the length of this * collection <i>only</i> if the caller knows that this collection does * not contain any <tt>null</tt> elements.) * * <p>If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements in * the same order. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a collection known to contain only strings. * The following code can be used to dump the collection into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param a the array into which the elements of this collection are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing all of the elements in this collection * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this collection * @throws NullPointerException if the specified array is null */ <T> T[] toArray(T[] a); // Modification Operations /** * Ensures that this collection contains the specified element (optional * operation). Returns <tt>true</tt> if this collection changed as a * result of the call. (Returns <tt>false</tt> if this collection does * not permit duplicates and already contains the specified element.)<p> * * Collections that support this operation may place limitations on what * elements may be added to this collection. In particular, some * collections will refuse to add <tt>null</tt> elements, and others will * impose restrictions on the type of elements that may be added. * Collection classes should clearly specify in their documentation any * restrictions on what elements may be added.<p> * * If a collection refuses to add a particular element for any reason * other than that it already contains the element, it <i>must</i> throw * an exception (rather than returning <tt>false</tt>). This preserves * the invariant that a collection always contains the specified element * after this call returns. * * @param e element whose presence in this collection is to be ensured * @return <tt>true</tt> if this collection changed as a result of the * call * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this collection * @throws ClassCastException if the class of the specified element * prevents it from being added to this collection * @throws NullPointerException if the specified element is null and this * collection does not permit null elements * @throws IllegalArgumentException if some property of the element * prevents it from being added to this collection * @throws IllegalStateException if the element cannot be added at this * time due to insertion restrictions */ boolean add(E e); /** * Removes a single instance of the specified element from this * collection, if it is present (optional operation). More formally, * removes an element <tt>e</tt> such that * <tt>(o==null ?

 e==null : o.equals(e))</tt>, if * this collection contains one or more such elements. Returns * <tt>true</tt> if this collection contained the specified element (or * equivalently, if this collection changed as a result of the call). * * @param o element to be removed from this collection, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the type of the specified element * is incompatible with this collection * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * collection does not permit null elements * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this collection */ boolean remove(Object o); // Bulk Operations /** * Returns <tt>true</tt> if this collection contains all of the elements * in the specified collection. * * @param c collection to be checked for containment in this collection * @return <tt>true</tt> if this collection contains all of the elements * in the specified collection * @throws ClassCastException if the types of one or more elements * in the specified collection are incompatible with this * collection * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) * @throws NullPointerException if the specified collection contains one * or more null elements and this collection does not permit null * elements * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>), * or if the specified collection is null. * @see #contains(Object) */ boolean containsAll(Collection<?

> c); /** * Adds all of the elements in the specified collection to this collection * (optional operation). The behavior of this operation is undefined if * the specified collection is modified while the operation is in progress. * (This implies that the behavior of this call is undefined if the * specified collection is this collection, and this collection is * nonempty.) * * @param c collection containing elements to be added to this collection * @return <tt>true</tt> if this collection changed as a result of the call * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this collection * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this collection * @throws NullPointerException if the specified collection contains a * null element and this collection does not permit null elements, * or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this * collection * @throws IllegalStateException if not all the elements can be added at * this time due to insertion restrictions * @see #add(Object) */ boolean addAll(Collection<? extends E> c); /** * Removes all of this collection‘s elements that are also contained in the * specified collection (optional operation). After this call returns, * this collection will contain no elements in common with the specified * collection. * * @param c collection containing elements to be removed from this collection * @return <tt>true</tt> if this collection changed as a result of the * call * @throws UnsupportedOperationException if the <tt>removeAll</tt> method * is not supported by this collection * @throws ClassCastException if the types of one or more elements * in this collection are incompatible with the specified * collection * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) * @throws NullPointerException if this collection contains one or more * null elements and the specified collection does not support * null elements * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>), * or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean removeAll(Collection<?> c); /** * Retains only the elements in this collection that are contained in the * specified collection (optional operation). In other words, removes from * this collection all of its elements that are not contained in the * specified collection. * * @param c collection containing elements to be retained in this collection * @return <tt>true</tt> if this collection changed as a result of the call * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation * is not supported by this collection * @throws ClassCastException if the types of one or more elements * in this collection are incompatible with the specified * collection * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>) * @throws NullPointerException if this collection contains one or more * null elements and the specified collection does not permit null * elements * (<a href="http://www.mamicode.com/#optional-restrictions">optional</a>), * or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean retainAll(Collection<?> c); /** * Removes all of the elements from this collection (optional operation). * The collection will be empty after this method returns. * * @throws UnsupportedOperationException if the <tt>clear</tt> operation * is not supported by this collection */ void clear(); // Comparison and hashing /** * Compares the specified object with this collection for equality. <p> * * While the <tt>Collection</tt> interface adds no stipulations to the * general contract for the <tt>Object.equals</tt>, programmers who * implement the <tt>Collection</tt> interface "directly" (in other words, * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt> * or a <tt>List</tt>) must exercise care if they choose to override the * <tt>Object.equals</tt>. It is not necessary to do so, and the simplest * course of action is to rely on <tt>Object</tt>‘s implementation, but * the implementor may wish to implement a "value comparison" in place of * the default "reference comparison." (The <tt>List</tt> and * <tt>Set</tt> interfaces mandate such value comparisons.)<p> * * The general contract for the <tt>Object.equals</tt> method states that * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and * only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt> * and <tt>Set.equals</tt> state that lists are only equal to other lists, * and sets to other sets. Thus, a custom <tt>equals</tt> method for a * collection class that implements neither the <tt>List</tt> nor * <tt>Set</tt> interface must return <tt>false</tt> when this collection * is compared to any list or set. (By the same logic, it is not possible * to write a class that correctly implements both the <tt>Set</tt> and * <tt>List</tt> interfaces.) * * @param o object to be compared for equality with this collection * @return <tt>true</tt> if the specified object is equal to this * collection * * @see Object#equals(Object) * @see Set#equals(Object) * @see List#equals(Object) */ boolean equals(Object o); /** * Returns the hash code value for this collection. While the * <tt>Collection</tt> interface adds no stipulations to the general * contract for the <tt>Object.hashCode</tt> method, programmers should * take note that any class that overrides the <tt>Object.equals</tt> * method must also override the <tt>Object.hashCode</tt> method in order * to satisfy the general contract for the <tt>Object.hashCode</tt> method. * In particular, <tt>c1.equals(c2)</tt> implies that * <tt>c1.hashCode()==c2.hashCode()</tt>. * * @return the hash code value for this collection * * @see Object#hashCode() * @see Object#equals(Object) */ int hashCode(); }

        从源代码中能够看出,Collection定义了一系列关于集合的基本操作,比方查看集合的大小size(),加入新的元素add()。清空集合clear()等。
        从集合接口图中,我们能够发现,Set,List,Queue。Deque继承了Collection。

说明这四个接口也相同是属于Collection,可是却又各不相同。

  • Set表示一个不能包括同样元素的集合。
  • List表示一个能够包括同样元素的有序集合。
  • Queue表示队列,数据的进出遵循First-In-First-Out原则。
  • Deque表示一个双向链表,既能够从表头操作链表,也能够从末端来操作链表。经常使用的详细实现有:LinkedList。
        Map是一个与Collection不一样的数据结构,主要是key->value数据结构。在程序中。该类数据结构常常会被用到。比方HttpServletRequest中获取參数,redis缓存,enchance缓存等,以下是Map接口的源代码:
public interface Map<K,V> {
    // Query Operations

    /**
     * Returns the number of key-value mappings in this map.  If the
     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of key-value mappings in this map
     */
    int size();

    /**
     * Returns <tt>true</tt> if this map contains no key-value mappings.
     *
     * @return <tt>true</tt> if this map contains no key-value mappings
     */
    boolean isEmpty();

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the specified
     * key.  More formally, returns <tt>true</tt> if and only if
     * this map contains a mapping for a key <tt>k</tt> such that
     * <tt>(key==null ?

k==null : key.equals(k))</tt>. (There can be * at most one such mapping.) * * @param key key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified * key * @throws ClassCastException if the key is of an inappropriate type for * this map * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified key is null and this map * does not permit null keys * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) */ boolean containsKey(Object key); /** * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. More formally, returns <tt>true</tt> if and only if * this map contains at least one mapping to a value <tt>v</tt> such that * <tt>(value=http://www.mamicode.com/=null ?

v==null : value.equals(v))</tt>. This operation * will probably require time linear in the map size for most * implementations of the <tt>Map</tt> interface. * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value * @throws ClassCastException if the value is of an inappropriate type for * this map * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified value is null and this * map does not permit null values * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) */ boolean containsValue(Object value); /** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>If this map permits null values, then a return value of * {@code null} does not <i>necessarily</i> indicate that the map * contains no mapping for the key; it‘s also possible that the map * explicitly maps the key to {@code null}. The {@link #containsKey * containsKey} operation may be used to distinguish these two cases. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or * {@code null} if this map contains no mapping for the key * @throws ClassCastException if the key is of an inappropriate type for * this map * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified key is null and this map * does not permit null keys * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) */ V get(Object key); // Modification Operations /** * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for * the key, the old value is replaced by the specified value. (A map * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only * if {@link #containsKey(Object) m.containsKey(k)} would return * <tt>true</tt>.) * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>, * if the implementation supports <tt>null</tt> values.) * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map */ V put(K key, V value); /** * Removes the mapping for a key from this map if it is present * (optional operation). More formally, if this map contains a mapping * from key <tt>k</tt> to value <tt>v</tt> such that * <code>(key==null ? k==null : key.equals(k))</code>, that mapping * is removed. (The map can contain at most one such mapping.) * * <p>Returns the value to which this map previously associated the key, * or <tt>null</tt> if the map contained no mapping for the key. * * <p>If this map permits null values, then a return value of * <tt>null</tt> does not <i>necessarily</i> indicate that the map * contained no mapping for the key; it‘s also possible that the map * explicitly mapped the key to <tt>null</tt>. * * <p>The map will not contain a mapping for the specified key once the * call returns. * * @param key key whose mapping is to be removed from the map * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this map * @throws ClassCastException if the key is of an inappropriate type for * this map * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified key is null and this * map does not permit null keys * (<a href="http://www.mamicode.com/Collection.html#optional-restrictions">optional</a>) */ V remove(Object key); // Bulk Operations /** * Copies all of the mappings from the specified map to this map * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(Object,Object) put(k, v)} on this map once * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the * specified map. The behavior of this operation is undefined if the * specified map is modified while the operation is in progress. * * @param m mappings to be stored in this map * @throws UnsupportedOperationException if the <tt>putAll</tt> operation * is not supported by this map * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map * @throws NullPointerException if the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values * @throws IllegalArgumentException if some property of a key or value in * the specified map prevents it from being stored in this map */ void putAll(Map<? extends K, ?

extends V> m); /** * Removes all of the mappings from this map (optional operation). * The map will be empty after this call returns. * * @throws UnsupportedOperationException if the <tt>clear</tt> operation * is not supported by this map */ void clear(); // Views /** * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator‘s own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * * @return a set view of the keys contained in this map */ Set<K> keySet(); /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. If the map is * modified while an iteration over the collection is in progress * (except through the iterator‘s own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * * @return a collection view of the values contained in this map */ Collection<V> values(); /** * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator‘s own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * * @return a set view of the mappings contained in this map */ Set<Map.Entry<K, V>> entrySet(); /** * A map entry (key-value pair). The <tt>Map.entrySet</tt> method returns * a collection-view of the map, whose elements are of this class. The * <i>only</i> way to obtain a reference to a map entry is from the * iterator of this collection-view. These <tt>Map.Entry</tt> objects are * valid <i>only</i> for the duration of the iteration; more formally, * the behavior of a map entry is undefined if the backing map has been * modified after the entry was returned by the iterator, except through * the <tt>setValue</tt> operation on the map entry. * * @see Map#entrySet() * @since 1.2 */ interface Entry<K,V> { /** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */ K getKey(); /** * Returns the value corresponding to this entry. If the mapping * has been removed from the backing map (by the iterator‘s * <tt>remove</tt> operation), the results of this call are undefined. * * @return the value corresponding to this entry * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */ V getValue(); /** * Replaces the value corresponding to this entry with the specified * value (optional operation). (Writes through to the map.) The * behavior of this call is undefined if the mapping has already been * removed from the map (by the iterator‘s <tt>remove</tt> operation). * * @param value new value to be stored in this entry * @return old value corresponding to the entry * @throws UnsupportedOperationException if the <tt>put</tt> operation * is not supported by the backing map * @throws ClassCastException if the class of the specified value * prevents it from being stored in the backing map * @throws NullPointerException if the backing map does not permit * null values, and the specified value is null * @throws IllegalArgumentException if some property of this value * prevents it from being stored in the backing map * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */ V setValue(V value); /** * Compares the specified object with this entry for equality. * Returns <tt>true</tt> if the given object is also a map entry and * the two entries represent the same mapping. More formally, two * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping * if<pre> * (e1.getKey()==null ?

* e2.getKey()==null : e1.getKey().equals(e2.getKey())) && * (e1.getValue()==null ?

* e2.getValue()==null : e1.getValue().equals(e2.getValue())) * </pre> * This ensures that the <tt>equals</tt> method works properly across * different implementations of the <tt>Map.Entry</tt> interface. * * @param o object to be compared for equality with this map entry * @return <tt>true</tt> if the specified object is equal to this map * entry */ boolean equals(Object o); /** * Returns the hash code value for this map entry. The hash code * of a map entry <tt>e</tt> is defined to be: <pre> * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ * (e.getValue()==null ? 0 : e.getValue().hashCode()) * </pre> * This ensures that <tt>e1.equals(e2)</tt> implies that * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries * <tt>e1</tt> and <tt>e2</tt>, as required by the general * contract of <tt>Object.hashCode</tt>. * * @return the hash code value for this map entry * @see Object#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); } // Comparison and hashing /** * Compares the specified object with this map for equality. Returns * <tt>true</tt> if the given object is also a map and the two maps * represent the same mappings. More formally, two maps <tt>m1</tt> and * <tt>m2</tt> represent the same mappings if * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the * <tt>equals</tt> method works properly across different implementations * of the <tt>Map</tt> interface. * * @param o object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map */ boolean equals(Object o); /** * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map‘s * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt> * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this map * @see Map.Entry#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); }

        在Map接口中,相同也定义了有关于Map的经常使用操作,比方插入数据put(),清空数据clear(),拿到key的Set集合keySet()。在这里面使用了一个Entry<K,V>接口来表示一个键值对。一个Map能够返回三种类型的集合,一种是Key组成的keySet()。一种是Value组成的values()。第二种则是由key,value组成的entrySet()。

泛型技术与集合框架

        在集合框架中,使用了大量的泛型技术。比方Collection<V>则代表了Collection使用了泛型,开发人员能够依据须要来选择V的详细内容。

比方Collection<String>,Collection<Integer>等。在泛型中,须要注意一下几点:

  • 泛型不能为基本数据类型(byte,char。short,int,float,double,boolean),假设须要基本数据类型,能够使用基本使用类型相应的包装类型来替代。(Byte。Character,Short,Integer,Float,Double,Boolean)
  • 泛型能够是集合框架的随意类型。初看java集合框架,会感觉该框架仅仅定义了几个接口,对于复杂数据结构的表达能力有所不够,可是通过泛型中嵌套集合框架。则能够实现复杂的数据。比方Map<List,Map<List,Map<String,List<String>>>>

详细实现

            有了总体上对java集合框架的基本认识。再理解整个集合框架中的设计便变得简单起来。下图是java集合框架的类图结构:
技术分享
        通过类型能够发现,这里面大量使用了AbstractXxx的类。这样子做的目的是什么呢?以下我们观察下AbstractList<E>的源代码:
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractList() {
    }

    /**
     * Appends the specified element to the end of this list (optional
     * operation).
     *
     * <p>Lists that support this operation may place limitations on what
     * elements may be added to this list.  In particular, some
     * lists will refuse to add null elements, and others will impose
     * restrictions on the type of elements that may be added.  List
     * classes should clearly specify in their documentation any restrictions
     * on what elements may be added.
     *
     * <p>This implementation calls {@code add(size(), e)}.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless
     * {@link #add(int, Object) add(int, E)} is overridden.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws UnsupportedOperationException if the {@code add} operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and this
     *         list does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this list
     */
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    /**
     * {@inheritDoc}
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    abstract public E get(int index);

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }


    // Search Operations

    /**
     * {@inheritDoc}
     *
     * <p>This implementation first gets a list iterator (with
     * {@code listIterator()}).  Then, it iterates over the list until the
     * specified element is found or the end of the list is reached.
     *
     * @throws ClassCastException   {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation first gets a list iterator that points to the end
     * of the list (with {@code listIterator(size())}).  Then, it iterates
     * backwards over the list until the specified element is found, or the
     * beginning of the list is reached.
     *
     * @throws ClassCastException   {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public int lastIndexOf(Object o) {
        ListIterator<E> it = listIterator(size());
        if (o==null) {
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }


    // Bulk Operations

    /**
     * Removes all of the elements from this list (optional operation).
     * The list will be empty after this call returns.
     *
     * <p>This implementation calls {@code removeRange(0, size())}.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless {@code remove(int
     * index)} or {@code removeRange(int fromIndex, int toIndex)} is
     * overridden.
     *
     * @throws UnsupportedOperationException if the {@code clear} operation
     *         is not supported by this list
     */
    public void clear() {
        removeRange(0, size());
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation gets an iterator over the specified collection
     * and iterates over it, inserting the elements obtained from the
     * iterator into this list at the appropriate position, one at a time,
     * using {@code add(int, E)}.
     * Many implementations will override this method for efficiency.
     *
     * <p>Note that this implementation throws an
     * {@code UnsupportedOperationException} unless
     * {@link #add(int, Object) add(int, E)} is overridden.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }


    // Iterators

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>This implementation returns a straightforward implementation of the
     * iterator interface, relying on the backing list‘s {@code size()},
     * {@code get(int)}, and {@code remove(int)} methods.
     *
     * <p>Note that the iterator returned by this method will throw an
     * {@link UnsupportedOperationException} in response to its
     * {@code remove} method unless the list‘s {@code remove(int)} method is
     * overridden.
     *
     * <p>This implementation can be made to throw runtime exceptions in the
     * face of concurrent modification, as described in the specification
     * for the (protected) {@link #modCount} field.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation returns {@code listIterator(0)}.
     *
     * @see #listIterator(int)
     */
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation returns a straightforward implementation of the
     * {@code ListIterator} interface that extends the implementation of the
     * {@code Iterator} interface returned by the {@code iterator()} method.
     * The {@code ListIterator} implementation relies on the backing list‘s
     * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
     * and {@code remove(int)} methods.
     *
     * <p>Note that the list iterator returned by this implementation will
     * throw an {@link UnsupportedOperationException} in response to its
     * {@code remove}, {@code set} and {@code add} methods unless the
     * list‘s {@code remove(int)}, {@code set(int, E)}, and
     * {@code add(int, E)} methods are overridden.
     *
     * <p>This implementation can be made to throw runtime exceptions in the
     * face of concurrent modification, as described in the specification for
     * the (protected) {@link #modCount} field.
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }

    private class Itr implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0;

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1;

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size();
        }

        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public E previous() {
            checkForComodification();
            try {
                int i = cursor - 1;
                E previous = get(i);
                lastRet = cursor = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor-1;
        }

        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.set(lastRet, e);
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                AbstractList.this.add(i, e);
                lastRet = -1;
                cursor = i + 1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * <p>This implementation returns a list that subclasses
     * {@code AbstractList}.  The subclass stores, in private fields, the
     * offset of the subList within the backing list, the size of the subList
     * (which can change over its lifetime), and the expected
     * {@code modCount} value of the backing list.  There are two variants
     * of the subclass, one of which implements {@code RandomAccess}.
     * If this list implements {@code RandomAccess} the returned list will
     * be an instance of the subclass that implements {@code RandomAccess}.
     *
     * <p>The subclass‘s {@code set(int, E)}, {@code get(int)},
     * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
     * Collection)} and {@code removeRange(int, int)} methods all
     * delegate to the corresponding methods on the backing abstract list,
     * after bounds-checking the index and adjusting for the offset.  The
     * {@code addAll(Collection c)} method merely returns {@code addAll(size,
     * c)}.
     *
     * <p>The {@code listIterator(int)} method returns a "wrapper object"
     * over a list iterator on the backing list, which is created with the
     * corresponding method on the backing list.  The {@code iterator} method
     * merely returns {@code listIterator()}, and the {@code size} method
     * merely returns the subclass‘s {@code size} field.
     *
     * <p>All methods first check to see if the actual {@code modCount} of
     * the backing list is equal to its expected value, and throw a
     * {@code ConcurrentModificationException} if it is not.
     *
     * @throws IndexOutOfBoundsException if an endpoint index value is out of range
     *         {@code (fromIndex < 0 || toIndex > size)}
     * @throws IllegalArgumentException if the endpoint indices are out of order
     *         {@code (fromIndex > toIndex)}
     */
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?

new RandomAccessSubList<>(this, fromIndex, toIndex) : new SubList<>(this, fromIndex, toIndex)); } // Comparison and hashing /** * Compares the specified object with this list for equality. Returns * {@code true} if and only if the specified object is also a list, both * lists have the same size, and all corresponding pairs of elements in * the two lists are <i>equal</i>. (Two elements {@code e1} and * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null : * e1.equals(e2))}.) In other words, two lists are defined to be * equal if they contain the same elements in the same order.<p> * * This implementation first checks if the specified object is this * list. If so, it returns {@code true}; if not, it checks if the * specified object is a list. If not, it returns {@code false}; if so, * it iterates over both lists, comparing corresponding pairs of elements. * If any comparison returns {@code false}, this method returns * {@code false}. If either iterator runs out of elements before the * other it returns {@code false} (as the lists are of unequal length); * otherwise it returns {@code true} when the iterations complete. * * @param o the object to be compared for equality with this list * @return {@code true} if the specified object is equal to this list */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List)) return false; ListIterator<E> e1 = listIterator(); ListIterator e2 = ((List) o).listIterator(); while (e1.hasNext() && e2.hasNext()) { E o1 = e1.next(); Object o2 = e2.next(); if (!(o1==null ?

o2==null : o1.equals(o2))) return false; } return !(e1.hasNext() || e2.hasNext()); } /** * Returns the hash code value for this list. * * <p>This implementation uses exactly the code that is used to define the * list hash function in the documentation for the {@link List#hashCode} * method. * * @return the hash code value for this list */ public int hashCode() { int hashCode = 1; for (E e : this) hashCode = 31*hashCode + (e==null ?

0 : e.hashCode()); return hashCode; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * * <p>This method is called by the {@code clear} operation on this list * and its subLists. Overriding this method to take advantage of * the internals of the list implementation can <i>substantially</i> * improve the performance of the {@code clear} operation on this list * and its subLists. * * <p>This implementation gets a list iterator positioned before * {@code fromIndex}, and repeatedly calls {@code ListIterator.next} * followed by {@code ListIterator.remove} until the entire range has * been removed. <b>Note: if {@code ListIterator.remove} requires linear * time, this implementation requires quadratic time.</b> * * @param fromIndex index of first element to be removed * @param toIndex index after last element to be removed */ protected void removeRange(int fromIndex, int toIndex) { ListIterator<E> it = listIterator(fromIndex); for (int i=0, n=toIndex-fromIndex; i<n; i++) { it.next(); it.remove(); } } /** * The number of times this list has been <i>structurally modified</i>. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. * * <p>This field is used by the iterator and list iterator implementation * returned by the {@code iterator} and {@code listIterator} methods. * If the value of this field changes unexpectedly, the iterator (or list * iterator) will throw a {@code ConcurrentModificationException} in * response to the {@code next}, {@code remove}, {@code previous}, * {@code set} or {@code add} operations. This provides * <i>fail-fast</i> behavior, rather than non-deterministic behavior in * the face of concurrent modification during iteration. * * <p><b>Use of this field by subclasses is optional.</b> If a subclass * wishes to provide fail-fast iterators (and list iterators), then it * merely has to increment this field in its {@code add(int, E)} and * {@code remove(int)} methods (and any other methods that it overrides * that result in structural modifications to the list). A single call to * {@code add(int, E)} or {@code remove(int)} must add no more than * one to this field, or the iterators (and list iterators) will throw * bogus {@code ConcurrentModificationExceptions}. If an implementation * does not wish to provide fail-fast iterators, this field may be * ignored. */ protected transient int modCount = 0; private void rangeCheckForAdd(int index) { if (index < 0 || index > size()) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size(); } } class SubList<E> extends AbstractList<E> { private final AbstractList<E> l; private final int offset; private int size; SubList(AbstractList<E> list, int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); l = list; offset = fromIndex; size = toIndex - fromIndex; this.modCount = l.modCount; } public E set(int index, E element) { rangeCheck(index); checkForComodification(); return l.set(index+offset, element); } public E get(int index) { rangeCheck(index); checkForComodification(); return l.get(index+offset); } public int size() { checkForComodification(); return size; } public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); l.add(index+offset, element); this.modCount = l.modCount; size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); E result = l.remove(index+offset); this.modCount = l.modCount; size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); l.removeRange(fromIndex+offset, toIndex+offset); this.modCount = l.modCount; size -= (toIndex-fromIndex); } public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize==0) return false; checkForComodification(); l.addAll(offset+index, c); this.modCount = l.modCount; size += cSize; return true; } public Iterator<E> iterator() { return listIterator(); } public ListIterator<E> listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); return new ListIterator<E>() { private final ListIterator<E> i = l.listIterator(index+offset); public boolean hasNext() { return nextIndex() < size; } public E next() { if (hasNext()) return i.next(); else throw new NoSuchElementException(); } public boolean hasPrevious() { return previousIndex() >= 0; } public E previous() { if (hasPrevious()) return i.previous(); else throw new NoSuchElementException(); } public int nextIndex() { return i.nextIndex() - offset; } public int previousIndex() { return i.previousIndex() - offset; } public void remove() { i.remove(); SubList.this.modCount = l.modCount; size--; } public void set(E e) { i.set(e); } public void add(E e) { i.add(e); SubList.this.modCount = l.modCount; size++; } }; } public List<E> subList(int fromIndex, int toIndex) { return new SubList<>(this, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } private void checkForComodification() { if (this.modCount != l.modCount) throw new ConcurrentModificationException(); } } class RandomAccessSubList<E> extends SubList<E> implements RandomAccess { RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) { super(list, fromIndex, toIndex); } public List<E> subList(int fromIndex, int toIndex) { return new RandomAccessSubList<>(this, fromIndex, toIndex); } }

        通过源代码能够发现。该类提供了List<E>的基本实现。对于不支持的操作,则直接抛出UnSupportedOperationException。其它之类直接继承该类。然后提供各自的实现。就可以实现同样模块的代码重用。
        如今相信通过类图中的结构,以及类的名字就可以猜到某个类的详细实现方式了吧。比方ArrayList能够猜到里面的数据结构是使用数组来实现的。LinkedList能够猜到里面是使用链表实现的。既然两者都能够作为List来使用。那两者之间就必定存在着相似点与不同点。

相似点就是大家都实现了List,提供了List应该具备的操作,不同点则是实现方式不同,对于有些操作的性能是有差异的。详细的差异。相比熟悉数据结构的人都明确。数组查询效率高,而链表则在插入数据时。更加高速。详细的,大家能够參考下数据结构的介绍。

        

总结

        初看java集合框架。肯定会被庞大的类体系结构给弄的晕乎晕乎的。

可是,作为一个java开发人员。集合框架不可缺少。在开发中,心中应该时刻明确。什么情况下,应该选择使用什么样的类来盛放数据。为了程序的课扩展性,也尽量保持对接口编程的风格。



java集合框架