ArrayList內部采用數組實現,隨機存取效率高O(1),刪除的效率就低O(N)。數組實現會保持插入的順序,而且允許重復元素。
LinkedList內部采用引用實現(對應C,C++中的鏈表),查詢的效率偏低O(N),但是適合插入和刪除頻繁的集合數據O(1)。

HashSet內部采用HashMap實現。因為使用Hash存取,所以不維護插入的順序且不允許重復元素。
TreeSet內部采用TreeMap實現

HashMap采用數組實現,數組中的每個元素是一個鏈表,元素的存取都是先計算Hash值,根據Hash值得到其在那個鏈表之中。然后在
 鏈表中依次進行比較。與Hashtable相比,Hashtable是線程安全且不允許null的key和value。
 下面是HashMap的get方法:

    public V get(Object key) {
        Object k = maskNull(key);
        int hash = hash(k);
        int i = indexFor(hash, table.length);
        Entry<K,V> e = table[i];
        while (true) {
            if (e == null)
                return null;
            if (e.hash == hash && eq(k, e.key))
                return e.value;
            e = e.next;
        }
    }
   
    Hash方法總體的效率都很高,包括插入、刪除和查詢O(1)。

TreeMap采用的是red-black tree來實現。TreeMap對key值進行排序,并且維護tree的balance,所以插入和刪除的效率偏低O(logN)。

下面是怎么選擇集合類的一個總結:

To close this chapter, let's take a quick look at some deciding factors in how to pick which standard collection implementation to use. These are not meant to be hard and fast rules but rather general guidelines to help you along.

1.If you need to store primitive elements, you must use an array unless you want to place every item into a wrapper class like Integer or Float. Consider using a BitSet instead of an array of booleans.

2.Rarely, if ever, should you use an historical collection class like Hashtable or Vector. Sometimes you need to use a Properties object, which is a type of Hashtable. Unless explicitly called for-as when using the JavaMail API-the historical collection class should be avoided in favor of the newer framework implementations.

3.Use a List if you need ordered access. Pick an ArrayList for indexed access. Definitely use a LinkedList when you need to add and remove elements from the beginning or middle of the list. If you only need ordered access through an Iterator, believe it or not, LinkedList is actually faster. Lists are also good if your collection requires the storing of duplicates, triplicates, or more.

4.Sets are for storing unique items in a collection. If you need ordered access, use a TreeSet. Otherwise, use a HashSet. If you only need ordered access after all the elements have been added, consider creating the set with a HashSet, then copying all the elements into a TreeSet.

5.Use a Map if you need to store key?value pairs and the key isn't an integer. (Consider using an array or List for indexed access.) Like Set, you should always use the hashed version of the collection (HashMap) unless you need sorted access (TreeMap).

6.Rely on the Collections class to make collections and maps read-only and thread-safe.

7.Use the WeakHashMap if you need to maintain weak references to keys stored in the map.