1. 程式人生 > >Java基礎之集合類如ArrayList、LinkedList、HashMap、HashTable的區別

Java基礎之集合類如ArrayList、LinkedList、HashMap、HashTable的區別

ArrayList是一個動態陣列,有下標

LinkedList是一個雙向連結串列,一個指標指向下一個

相同點:都繼承自Collections類,放動態資料。

不同點:

後者有指標,增加一個數據,只用斷開一個連線,分別將新資料連上

刪除一個數據,區別在於如果這個資料位於陣列中間,後者只用查到該資料,斷開一個連線,將兩邊的資料連上;

而前者需要將後面所有資料移位

修改,對於後者來說,就是刪除+增加;而後者需要移位。

查詢,前者通過下標查詢方便,後者需要一個指標指向下一個指標來尋找資料,比較慢。

offer==add:新增一個值到尾部,offer是使用add方法實現的。

peek:獲得第1個值。

pop:獲得第1個值並刪除。

poll:獲得第1個值並刪除,與pop不同的是如果第1個值為null,pop丟擲NoSuchElementException,而poll僅返回null。

Vector使用陣列實現,其實跟ArrayList一樣,區別僅在於實現同步,即不同執行緒可以共用一個數據。但它不會對遍歷如iterator加鎖,僅set、get、remove等常用操作加鎖,在這一點上HashTable同理。

HashMap底層使用陣列+連結串列實現,同一個鍵可以放多個值,但取出的是最後一個,非同步,允許放空值空鍵

HashTable與HashMap一樣,唯一不同就是,它是執行緒安全的,put、get等操作都加鎖,且不允許空值空鍵

查詢都根據key的hash來定位陣列的下標。

LinkedHashMap與LinkedArrayList原理相似,可以放空值空鍵,非同步;相比HashMap是個單向連結串列來講,它是個雙向連結串列,可以不像單向連結串列一樣從頭開始查詢資料,是單向連結串列的升級;缺點:保留原值。

我們能否讓HashMap同步?可以通過下面語句同步:

Map map=Collections.sychronizedMap(hashmap);

如果要完全的執行緒安全可以考慮CopyOnWriteArrayList和ConcurrentHashMap。它們使用volatile和synchronzied來保持同步。

 Collections.unmodifiableList(list);
上面的方法可使當前list無法再新增物件,保持資料傳遞的安全性。Android提供一個新的API:SpareArray,來替換ArrayList,特點不存空值,在跟下標有關的操作中,都會執行一遍回收操作,將空值移除提高查詢和增加效率。

Hash:指標對一段資料做的指紋(fingerprint)或者叫摘要(diget),用於快速查詢。hash一般保證值不相等,防止暴力碰撞和篡改; 如果值相等,則需要繼續當前演算法,直到不等為止(再雜湊法),還有開放定址法、再建公共溢位區法等等。常見的hash演算法有Md5和Sha等。

比如HashMap,查詢時不是比較key,而是比較key的hash值,則速度更快。

再比如ArrayMap,使用陣列結構,儲存hash陣列和value陣列。put時,根據key和key得到的hash,來設計value的儲存位置index,然後把舊值返回,將新的value存入; get時,根據key和key得到的hash,計算出index,從value陣列中取得目標value。

最簡單的就是String物件裡的hashCode演算法:

	public static int hashCode(char[] value) {
		int h = hash;
		if (h == 0 && value.length > 0) {
			char val[] = value;

			for (int i = 0; i < value.length; i++) {
				h = 31 * h + val[i];
			}
			hash = h;
		}
		return h;
	}

TreeSet、TreeMap是自動排序的,TreeSet使用TreeMap來實現。

TreeSet:

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{
    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;
  public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }

   private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden stuff
        s.defaultReadObject();

        // Read in Comparator
        @SuppressWarnings("unchecked")
            Comparator<? super E> c = (Comparator<? super E>) s.readObject();

        // Create backing TreeMap
        TreeMap<E,Object> tm = new TreeMap<>(c);
        m = tm;

        // Read in size
        int size = s.readInt();

        tm.readTreeSet(size, s, PRESENT);
    }

TreeMap: 通過Comparator介面實現升級排序

    public V put(K key, V value) {
        TreeMapEntry<K,V> t = root;
        if (t == null) {
            // We could just call compare(key, key) for its side effect of checking the type and
            // nullness of the input key. However, several applications seem to have written comparators
            // that only expect to be called on elements that aren't equal to each other (after
            // making assumptions about the domain of the map). Clearly, such comparators are bogus
            // because get() would never work, but TreeSets are frequently used for sorting a set
            // of distinct elements.
            //
            // As a temporary work around, we perform the null & instanceof checks by hand so that
            // we can guarantee that elements are never compared against themselves.
            //
            // compare(key, key);
            //
            // **** THIS CHANGE WILL BE REVERTED IN A FUTURE ANDROID RELEASE ****
            if (comparator != null) {
                if (key == null) {
                    comparator.compare(key, key);
                }
            } else {
                if (key == null) {
                    throw new NullPointerException("key == null");
                } else if (!(key instanceof Comparable)) {
                    throw new ClassCastException(
                            "Cannot cast" + key.getClass().getName() + " to Comparable.");
                }
            }

            root = new TreeMapEntry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        TreeMapEntry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        TreeMapEntry<K,V> e = new TreeMapEntry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }

附Java層次關係圖:

如圖所示:圖中,實線邊框的是實現類,折線邊框的是抽象類,而點線邊框的是介面 



有關集合類的排序和其他介紹請移步: