Java Hashtable Source Code (JDK8)

Source: Internet
Author: User
Tags rehash

Recorded HashMap also come to see Hashtable bar, recently intends to change an internship, so want to see the book review, otherwise it will soon remember ... Embarrassed AH ah, memory is too bad how to break???

Some variables inside the hashtable:

entry<?,? >[] table:hashtable uses the "zipper method" to implement a hash table, each Entry represents a key-value pair (key-value).

transient int count:hashtable The number of key-value pairs;

The threshold value of the private int threshold:hashtable (Threshols = capacity * Loadfactor);

Float loadfactor: Loading factor;

transient int modcount:hashtable The number of times modified to implement the Fast-fail mechanism. The fast-fail mechanism is in the concurrency collection, when it iterates, and if other threads make structural modifications to it, the iterator immediately senses and throws the concurrentmodificationexception exception.

Hashtable is defined as follows:

1  Public class Hashtable<k,v>2     extends dictionary<k,v>3     implements Map <K,V>, cloneable, java.io.Serializable {4     ... 5 }

It can be seen that Hashtable implements the map interface and inherits the dictionary class. The map interface is an object that maps keys to values. A map cannot contain duplicate keys, and each key can be mapped to at most one value. DictionaryA class is an abstract parent of any class (such as) that can map a key to a corresponding value Hashtable . Each key and each value is an object. In any Dictionary object, each key is associated with at most one value. Given a Dictionary and a key, you can find the associated element. Any non- null object can be used as a key or a value.

Look at the implementation of the commonly used constructors for Hashtable:

Default constructor: Capacity is 11, load factor is 0.75

1  Public Hashtable () {2          This (One, 0.75f); 3     }

Constructs with the specified initial capacity and the default load factor:

1  Public Hashtable (int  initialcapacity) {2this         (initialcapacity, 0.75f ); 3     }

Constructs with the specified initial capacity and the specified load factor:

1   PublicHashtable (intInitialcapacity,floatloadfactor) {2              //validation of parameter legitimacy3             if(Initialcapacity < 0)4                 Throw NewIllegalArgumentException ("Illegal capacity:" +5 initialcapacity);6             if(loadfactor <= 0 | |Float.isnan (loadfactor))7                 Throw NewIllegalArgumentException ("Illegal Load:" +loadfactor);8             9             if(initialcapacity==0)Teninitialcapacity = 1; One              This. Loadfactor =Loadfactor; A             //initializes the table array with the specified capacity -Table =Newentry<?,? >[initialcapacity]; -             //Calculating the valve value of a table theThreshold = (int) math.min (initialcapacity * loadfactor, max_array_size + 1); -}

Let's look at the put method and the Get method:

The first is the put method, the whole process of the Put method is: Calculate the hash value of the key, according to the hash value of key in the table array index position, and then iterate the key at the entry linked list (we understand for a list), if there is a key object in the list, Then replace the value directly with it, otherwise insert the Key-value node at the index position. Note that Hashtable is not allowed for null values.

int index = (hash & 0x7FFFFFFF)% tab.length--> The hash value of the key may be negative, through a "and" operation, the hash value is converted to a positive number, and then the resulting hash value and the length of the Hashtable to seek redundancy

1  //Synchronous Implementation2       Public synchronizedv put (K key, V value) {3             //Check value value is null4             if(Value = =NULL) {5                 Throw Newnullpointerexception ();6             }7 8             //makes sure the key is not already in the Hashtable.9entry<?,? > tab[] =table;Ten             //calculates the hash value of a key One             inthash =Key.hashcode (); A             //The following table in the table array is calculated by the hash value -             intIndex = (hash & 0x7FFFFFFF)%tab.length; -@SuppressWarnings ("Unchecked") theEntry<k,v> Entry = (entry<k,v>) Tab[index]; -             //Traverse, look for the key, find replace old value -              for(; Entry! =NULL; Entry =entry.next) { -                 if((Entry.hash = = hash) &&entry.key.equals (Key)) { +V old =Entry.value; -Entry.value =value; +                     returnOld ; A                 } at             } -             //is not found, the key is added to the - addentry (hash, key, value, index); -             return NULL; -         } -          Private voidAddEntry (intHash, K key, V value,intindex) { in                  //Modify linked list, Modcount self-increment -modcount++; to      +entry<?,? > tab[] =table; -                 if(Count >=threshold) { the                     //Rehash The table if the threshold is exceeded * rehash (); $tab =table;Panax Notoginsenghash =Key.hashcode (); -Index = (hash & 0x7FFFFFFF)%tab.length; the                 } +      A                 //creates the new entry. the@SuppressWarnings ("Unchecked") +Entry<k,v> e = (entry<k,v>) Tab[index]; -Tab[index] =NewEntry<>(hash, key, value, e); $count++; $}

The Get method is also synchronous, with the following specific implementations:

1   Public synchronizedV get (Object key) {2entry<?,? > tab[] =table;3             //calculates the hash value of a key4             inthash =Key.hashcode ();5             //The following table in the table array is calculated by the hash value6             intIndex = (hash & 0x7FFFFFFF)%tab.length;7             //Traverse Find key, locate the value that corresponds to the key value8              for(entry<?,? > E = tab[index]; E! =NULL; E =e.next) {9                 if((E.hash = = hash) &&e.key.equals (Key)) {Ten                     return(V) e.value; One                 } A             } -             return NULL; -}

Java Hashtable Source Code (JDK8)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.