Java8源碼-Hashtable(1)__hashtable

來源:互聯網
上載者:User

前面已經學習了HashMap的源碼,今天開始學習Hashtable。參考的JDK版本為1.8。(ps:以前都沒注意到Hashtable中的t是小寫。。。)

相信大家對Hashtable已經有所瞭解了,Hashtable和HashMap,從儲存結構和實現來講基本上都是相同的。它和HashMap的最大的不同是它是安全執行緒的,另外它不允許key和value為null。Hashtable是個過時的集合類,不建議在新代碼中使用,不需要安全執行緒的場合可以用HashMap替換,需要安全執行緒的場合可以用ConcurrentHashMap替換。但這並不是我們不去瞭解它的理由。最起碼Hashtable和HashMap的面試題在面試中經常被問到。Hashtable是如何?安全執行緒的的。Hashtable和HashMap的相同點和不同點。本文將分析Hashtable的內部結構及實現原理,協助大家學習HashMap和Hashtable。 頂部注釋

This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.

這個類是雜湊表的實現,key與value索引值對的映射集。任何非null的對象可以用作key或者vlaue。

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

為了能在雜湊表中成功地儲存和取出對象,用作key的對象必須實現hashCode方法和equals方法。

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

一個Hashtable的執行個體有兩個影響它行為的參數:初始化容量initial capacity 和負載因子load factor。容量是雜湊表中桶的數量,初始化容量是雜湊表被建立時的容量。雜湊表是開放的,就雜湊碰撞來說,一個桶儲存數個必須被順序尋找的node。負載因子是雜湊表在自動擴容之前可以多滿的一個度量(雜湊表幾乎不會在滿時才會擴容,載入因子越大,在擴容前雜湊表可以存放的節點就越多)。初始化容量initial capacity 和負載因子load factor僅僅對實現有細微的暗示。何時擴容,是否擴容取決於具體的實現。

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

一般來說,預設的載入因子0.75在雜湊表和時間和空間花銷上是一個很好的平衡。更高的載入因子減少了空間開銷但增加了尋找操作的時間開銷(影響了大多的雜湊表操作,包括get和put操作)。

The initial capacity controls a tradeoff between wasted space and the need for rehash operations, which are time-consuming. No rehash operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor. However, setting the initial capacity too high can waste space.

初始化容量initial capacity在空間開銷和擴容操作的時間開銷之間控制平衡。如果initial capacity大於雜湊表含有的node的數量/load factor,雜湊表就不會擴容。然而,把initial capacity設定地太高就增大空間開銷。

If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

如果提前知道hashtable將要存放許多node,建立hashtable時將initial capacity適當地設定地高些會使增加元素變得更有效率,否則容量不夠大將導致頻繁的擴容。

This example creates a hashtable of numbers. It uses the names of the numbers as keys:
Hashtable<String, Integer> numbers= new Hashtable<String, Integer>();
numbers.put(“one”, 1);
numbers.put(“two”, 2);
numbers.put(“three”, 3);}
To retrieve a number, use the following code:
Integer n = numbers.get(“two”);
if (n != null) {
System.out.println(“two = ” + n);
}}

這個例子示範了如何建立hashtable,存放元素,取出元素。

The iterators returned by the iterator method of the collections returned by all of this class’s “collection view methods” are fail-fast: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable’s keys and elements methods are not fail-fast.

iterator方法返回的迭代器是fail-fast的。如果在迭代器被建立後hashtable被結構型地修改了,除了迭代器自己的remove方法,迭代器會拋出一個ConcurrentModificationException異常。因此,面對在並發的修改,迭代器乾脆利落的失敗,而不是冒險的繼續。雜湊表的key和元素集合返回的Enumerations不是fail-fast的。

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

迭代器的fail-fast機制並不能得到保證,它不能夠保證一定出現該錯誤。一般來說,fail-fast會盡最大努力拋出ConcurrentModificationException異常。因此,為提高此類操作的正確性而編寫一個依賴於此異常的程式是錯誤的做法,正確做法是:ConcurrentModificationException 應該僅用於檢測 bug。

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the collection。

自從Java2開始,Hashtable繼承Map介面,成為了容器中的一員。

Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use java.util.concurrent.ConcurrentHashMap in place of Hashtable.

和新的集合實現不同,Hashtable是安全執行緒的。如果不需要安全執行緒的實現是不需要的,推薦使用HashMap代替Hashtable。如果需要安全執行緒的實現,推薦使用java.util.concurrent.ConcurrentHashMap代替Hashtable。

@author Arthur van Hoff
@author Josh Bloch
@author Neal Gafter
@see Object#equals(java.lang.Object)
@see Object#hashCode()
@see Hashtable#rehash()
@see Collection
@see Map
@see HashMap
@see TreeMap
@since JDK1.0

看完了上面的內容,大家應該能感覺到Hashtable確實和HashMap很相似。

下篇文章將繼續講解Hashtable。

本文已收錄於Java8容器源碼劄記專欄。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.