Hashtable 和 HashMap的區別

來源:互聯網
上載者:User

我們先看2個類的定義

public class Hashtable    extends Dictionary    implements Map, Cloneable, java.io.Serializable
public class HashMap    extends AbstractMap    implements Map, Cloneable, Serializable

可見Hashtable 繼承自 Dictiionary 而 HashMap繼承自AbstractMap

Hashtable的put方法如下

  public synchronized V put(K key, V value) {  //###### 注意這裡1    // Make sure the value is not null    if (value == null) { //###### 注意這裡 2      throw new NullPointerException();    }    // Makes sure the key is not already in the hashtable.    Entry tab[] = table;    int hash = key.hashCode(); //###### 注意這裡 3    int index = (hash & 0x7FFFFFFF) % tab.length;    for (Entry e = tab[index]; e != null; e = e.next) {      if ((e.hash == hash) && e.key.equals(key)) {        V old = e.value;        e.value = value;        return old;      }    }    modCount++;    if (count >= threshold) {      // Rehash the table if the threshold is exceeded      rehash();      tab = table;      index = (hash & 0x7FFFFFFF) % tab.length;    }    // Creates the new entry.    Entry e = tab[index];    tab[index] = new Entry(hash, key, value, e);    count++;    return null;  }

注意1 方法是同步的
注意2 方法不允許value==null
注意3 方法調用了key的hashCode方法,如果key==null,會拋出null 指標異常 HashMap的put方法如下

  public V put(K key, V value) { //###### 注意這裡 1    if (key == null)  //###### 注意這裡 2      return putForNullKey(value);    int hash = hash(key.hashCode());    int i = indexFor(hash, table.length);    for (Entry e = table[i]; e != null; e = e.next) {      Object k;      if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {        V oldValue = e.value;        e.value = value;        e.recordAccess(this);        return oldValue;      }    }    modCount++;    addEntry(hash, key, value, i);  //###### 注意這裡     return null;  }

注意1 方法是非同步的
注意2 方法允許key==null
注意3 方法並沒有對value進行任何調用,所以允許為null

補充:
Hashtable 有一個 contains方法,容易引起誤會,所以在HashMap裡面已經去掉了
當然,2個類都用containsKey和containsValue方法。

結論: ashMap 在大多數情況下是優先選擇的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.