Java Collection-hashtable

Source: Internet
Author: User
Tags rehash

Overview

Like HashMap, Hashtable is also a hash table that stores content that is a key-value pair.

Hashtable is defined in Java as:

 Public class Hashtable<k,v>    extends dictionary<k,v>    implements

From the source, we can see that Hashtable inherited from the Dictionary class, the implementation of the Map, cloneable, java.io.Serializable interface. Where the dictionary class is the abstract parent class of any class (such as Hashtable) that can map keys to corresponding values, each key and value is an object.

Member variables

Hashtable is a hash table implemented by the "zipper Method". It includes several important member variables: table, Count, Threshold, Loadfactor, Modcount.

    • Table is a entry[] array type, and Entry (explained in HashMap) is actually a one-way list. The hash table's "Key-value Key-value pairs" are stored in the entry array.
    • Count is the size of the Hashtable, which is the number of key-value pairs saved by Hashtable.
    • The threshold is the Hashtable threshold that is used to determine whether the Hashtable capacity needs to be adjusted. The value of threshold = "capacity * load factor".
    • Loadfactor is the loading factor.

Modcount is used to implement the fail-fast mechanism.

/*** the hash table data. */    Private transientEntry<k,v>[] table; /*** The total number of entries in the hash table. */    Private transient intcount; /*** The table is rehashed when it size exceeds this threshold.     (The * value of this field is (int) (capacity * loadfactor).) *     * @serial     */    Private intthreshold; /*** The load factor for the hashtable. *     * @serial     */    Private floatLoadfactor; /*** The number of times this Hashtable have been structurally modified * Structural modifications is those that  The number of entries in * the Hashtable or otherwise modify its internal structure (e.g., * rehash).  This field was used to make iterators on Collection-views of * the Hashtable fail-fast.     (see Concurrentmodificationexception). */    Private transient intModcount = 0;
Construction method

Hashtable provides a total of 4 construction methods:

      • public Hashtable(int initialCapacity, float loadFactor): Constructs a new empty hash table with the specified initial capacity and the specified load factor. Usealthashing is Boolean and, if True, executes the string key of another hash to reduce the occurrence of a hash conflict caused by weak hash calculations.
      • public Hashtable(int initialCapacity): Constructs a new empty hash table with the specified initial capacity and the default load factor (0.75).
      • public Hashtable(): The default constructor, with a capacity of 11 and a load factor of 0.75.
      • public Hashtable(Map<? extends K, ? extends V> t): Constructs a new hash table that has the same mapping relationship as the given map.
/*** Constructs a new, empty hashtable with the specified initial * capacity and the specified load factor. *     * @paraminitialcapacity The initial capacity of the Hashtable. * @paramloadfactor The load factor of the hashtable. * @exceptionIllegalArgumentException If the initial capacity is less * than zero, or if the load factor is NONP     Ositive. */     PublicHashtable (intInitialcapacity,floatloadfactor) {        if(Initialcapacity < 0)            Throw NewIllegalArgumentException ("Illegal capacity:" +initialcapacity); if(loadfactor <= 0 | |Float.isnan (loadfactor))Throw NewIllegalArgumentException ("Illegal Load:" +loadfactor); if(initialcapacity==0) initialcapacity= 1;  This. Loadfactor =Loadfactor; Table=NewEntry[initialcapacity]; Threshold= (int) math.min (initialcapacity * loadfactor, max_array_size + 1); Usealthashing= sun.misc.VM.isBooted () &&(initialcapacity>=holder.alternative_hashing_threshold); }    /*** Constructs a new, empty hashtable with the specified initial capacity * and default load factor (0.75). *     * @paraminitialcapacity The initial capacity of the Hashtable. * @exceptionIllegalArgumentException If the initial capacity is less * than zero. */     PublicHashtable (intinitialcapacity) {         This(Initialcapacity, 0.75f); }    /*** Constructs a new, empty hashtable with a default initial capacity (one) * and load factor (0.75). */     PublicHashtable () { This(One, 0.75f); }    /*** Constructs a new hashtable with the same mappings as the given * Map. The Hashtable is created with an initial capacity sufficient to * hold the mappings in the given Map and a default Loa     D factor (0.75). *     * @paramt The map whose mappings is is placed in this map. * @throwsNullPointerException If the specified map is null. * @since1.2*/     PublicHashtable (map<?extendsK?extendsV>t) { This(Math.max (2*t.size (), one), 0.75f);    Putall (t); }
Put method

The entire process for the Put method is:

    1. Determines whether value is empty, and throws an exception if it is empty;
    2. Calculates the hash value of key and obtains the position of key in the table array according to the hash value index, if the Table[index] element is not empty, then iterates, and if it encounters the same key, it is replaced directly and returns the old value;
    3. Otherwise, we can insert it into the table[index] position.

Some comments are also made in the following code:

 Public synchronizedv put (K key, V value) {//Make sure the value was not NULL to ensure that value is not null        if(Value = =NULL) {            Throw NewNullPointerException (); }        //makes sure the key is not already in the Hashtable. //Make sure key is not in Hashtable//first, the hash value of key is computed by hashing, and the index value is calculated to determine its position in table[].//second, iterate over the linked list of index indices, replace value if the linked list at that location exists with the same key, and return the old valueEntry tab[] =table; inthash =hash (key); intIndex = (hash & 0x7FFFFFFF)%tab.length;  for(entry<k,v> e = Tab[index]; E! =NULL; E =e.next) {if((E.hash = = hash) &&e.key.equals (Key)) {V old=E.value; E.value=value; returnOld ; }} Modcount++; if(Count >=threshold) {            //Rehash The table if the threshold is exceeded//rehash operation if the threshold is exceededrehash (); tab=table; Hash=hash (key); Index= (hash & 0x7FFFFFFF)%tab.length; }        //creates the new entry. //inserts a value, returns a nullEntry<k,v> e =Tab[index]; //creates a new entry node, inserts a new entry into the index position of the hashtable, and sets E as the next element of the new entryTab[index] =NewEntry<>(hash, key, value, E); Count++; return NULL; }

Illustrate this process with a practical example:

Suppose we now have hashtable capacity of 5, already exist (5,5), (13,13), (16,16), (17,17), (21,21) These 5 key value pairs, the current position of them in Hashtable is as follows:

Now, we insert a new key-value pair, put (16,22), assuming that the index of KEY=16 is 1. But now there are two entry in the position of index 1, so the program iterates over the linked list. During the iteration, it was found that one of the entry keys is the same as the key value pair we are inserting, so now the job is to replace the newvalue=22 with oldvalue=16 and return to oldvalue=16.

Then we now insert one, put (33,33), the index of KEY=33 is 3, and there is no key=33 entry in the list, so insert the node in the first position of the list.

Get method

The Get method is much simpler compared to the Put method. The process is to first obtain the hash value of the key by the hash () method, and then the index is indexed according to the hash value (the algorithm used in the above two steps is the same as the Put method). The linked list is then iterated, returning the corresponding value of the matching key, or null if not found.

 Public synchronizedV get (Object key) {Entry tab[]=table; inthash =hash (key); intIndex = (hash & 0x7FFFFFFF)%tab.length;  for(entry<k,v> e = Tab[index]; E! =NULL; E =e.next) {if((E.hash = = hash) &&e.key.equals (Key)) {                returnE.value; }        }        return NULL; }
Hashtable Traversal mode

Hashtable has several traversal methods:

//1. Use keys ()Enumeration<string> EN1 =Table.keys ();  while(En1.hasmoreelements ()) {en1.nextelement ();}//2. Using elements ()Enumeration<string> en2 =table.elements ();  while(En2.hasmoreelements ()) {en2.nextelement ();}//3. Using keyset ()Iterator<string> it1 =Table.keyset (). iterator ();  while(It1.hasnext ()) {It1.next ();}//4. Using EntrySet ()iterator<entry<string, string>> it2 =Table.entryset (). iterator ();  while(It2.hasnext ()) {It2.next ();}
A simple comparison between Hashtable and HashMap
    1. HashTable is based on the Dictionary class, and HashMap is based on Abstractmap. Dictionary is the abstract parent of any class that can map keys to corresponding values, and Abstractmap is an implementation based on the map interface to minimize the work required to implement this interface.
    2. Both the HASHMAP key and value are allowed to be null, and Hashtable's key and value are not allowed to be null. When HashMap encounters a key that is null, the Putfornullkey method is called for processing, and the value is not processed; Hashtable encounters null and returns nullpointerexception directly.
    3. The Hashtable method is synchronous, while HashMap is not. We can look at the source code, almost all public methods in Hashtable are synchronized, and some methods are also implemented internally through synchronized code blocks. So some people generally recommend that if it involves multithreading synchronization when using HashTable, not involved in the use of HASHMAP, but there is a static method in the Collections class: Synchronizedmap (), the method creates a thread-safe Map object, and returns it as a encapsulated object.

Java Collection-hashtable

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.