HashMap and Hashtable differences in Java

Source: Internet
Author: User
Tags rehash knowledge base java se

Hashtable and HashMap are fairly easy to ask in the Java interview, and even become the most frequently asked questions in the collection framework interview, so don't forget to prepare the question before you take any Java interview.

Let's first look at the definition of 2 classes.

 Public class Hashtable       extends Dictionary       Implements class= ' Replace_word ' title= "Java se Knowledge Base" target= ' _blank ' style= ' color: #df3434; Font-weight:bold; ' >java</a>.io. Serializable  
 Public class HashMap       extends Abstractmap       Implements Map, Cloneable, Serializable  

Visible hashtable inherit from Dictiionary and HashMap inherit from Abstractmap

The Put method of Hashtable is as follows

 Public synchronizedV Put (K key, V value) {//###### Note here 1//Make sure the value was not null  if(Value = =NULL) {//###### Note here 2    Throw NewNullPointerException (); }    //makes sure the key is not already in the Hashtable. Entry tab[] =table; inthash = Key.hashcode ();//###### Note here 3  intIndex = (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; returnOld ; }} Modcount++; if(Count >=threshold) {      //Rehash The table if the threshold is exceededrehash (); tab=table; Index= (hash & 0x7FFFFFFF)%tab.length; }    //creates the new entry. Entry e =Tab[index]; Tab[index]=NewEntry (hash, key, value, E); Count++; return NULL; }  

Note The 1 method is synchronous
Note the 2 method does not allow Value==null
Note the 3 method calls the Hashcode method of key, and if key==null, throws a null pointer exception

The Put method of HashMap is as follows

 PublicV Put (K key, V value) {//###### Note here 1  if(Key = =NULL)//###### Note here 2    returnPutfornullkey (value); inthash =Hash (Key.hashcode ()); inti =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); returnOldValue; }} Modcount++;  AddEntry (hash, key, value, I); //######, watch this .  return NULL; }  

Note The 1 method is non-synchronous
Note The 2 method allows key==null
Note the 3 method does not make any calls to value, so allow null

Whether to provide a contains method

HashMap hashtable contains method removed, changed to Containsvalue and ContainsKey, because the contains method is easy to cause misunderstanding.

Hashtable retains the Contains,containsvalue and ContainsKey three methods, where contains and Containsvalue function the same.

Let's take a look at Hashtable's ContainsKey method and Containsvalue source code:

 Public Boolean Containsvalue (Object value) {           return  contains (value);       }  
//determine if Hashtable contains "value"  Public synchronized Booleancontains (Object value) {//Note that value in Hashtable cannot be null,//if NULL, throw an exception!      if(Value = =NULL) {               Throw NewNullPointerException (); }               //to traverse the elements in the table array (Entry) from the back forward//for each entry (one-way linked list), iterate through each to determine whether the value of the node equals valueEntry tab[] =table;  for(inti = tab.length; i--> 0 ;) {                for(entry<k,v> e = tab[i]; E! =NULL; E =e.next) {if(E.value.equals (value)) {return true; }               }           }           return false; }  
//determine if Hashtable contains key  Public synchronized BooleanContainsKey (Object key) {Entry tab[]=table; /calculate the hash value and replace it directly with the hashcode of keyinthash =Key.hashcode (); //computes the index value in the array     intIndex = (hash & 0x7FFFFFFF)%tab.length; //find "key corresponding to the entry (linked list)", and then in the list to find "hash value" and "key value" and key are equal to the elements      for(entry<k,v> e = Tab[index]; E! =NULL; E =e.next) {if((E.hash = = hash) &&e.key.equals (Key)) {                   return true; }           }           return false; }  

Let's take a look at HashMap's ContainsKey method and Containsvalue source code:

// whether the HashMap contains      key     Public Boolean ContainsKey (Object key) {              returnnull;          }  
//returns the key value pair for key    FinalEntry<k,v>getentry (Object key) {//Get hash value//HashMap the "key is null" element is stored in the table[0] position, "key is not NULL" is called hash () to calculate the hash value        inthash = (Key = =NULL) ? 0: Hash (Key.hashcode ()); //Look for the " key value equals key" element on "linked list for this hash value "         for(Entry<k,v> e =table[indexfor (hash, table.length)]; E!=NULL; E=e.next) {Object k; if(E.hash = = Hash &&((k= e.key) = = Key | | (Key! =NULL&&Key.equals (k)))) returne; }              return NULL; }  
//whether to include the element "value is "     Public BooleanContainsvalue (Object value) {//If "value is null", call Containsnullvalue () to find    if(Value = =NULL)                  returnContainsnullvalue (); //If "value is not NULL", look for a node in HashMap that has value values. entry[] Tab =table;  for(inti = 0; i < tab.length; i++)                   for(Entry e = tab[i]; E! =NULL; E =e.next)if(Value.equals (e.value))return true; return false; }  

From the above source comparison, we can get the following different places: key and value whether null values are allowed.

Where key and value are objects and cannot contain duplicate keys, but can contain duplicate value. Through the above ContainsKey method and the source code of Containsvalue we can clearly see:

In Hashtable, both key and value do not allow null values. However, if there is an action like put (Null,null) in Hashtable, the compilation can also pass because both the key and the value are object types, but the runtime throws a NullPointerException exception, which is the specification of the JDK.

In HashMap, NULL can be used as a key with only one key, and one or more keys can have a value of NULL. When the Get () method returns a null value, the key may not be in HashMap, or the value corresponding to the key may be null. Therefore, the get () method cannot be used in HashMap to determine whether a key exists in HashMap and should be judged by the ContainsKey () method.

The difference between HashMap and Hashtable

HashMap and Hashtable both implement the map interface, but decide which one to use before you start to figure out the difference between them. The main differences are: thread safety, Synchronization (synchronization), and speed.

1.HashMap can almost be equivalent to Hashtable, except that HashMap is non-synchronized and can accept null (a key value (key) and a value that the HashMap can accept as null (value), and Hashtable does not).

HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation), and they all complete the map interface.

The main difference is that HASHMAP allows null (NULL) key values (key), which may be more efficient than Hashtable due to non-thread safety.

HashMap allows NULL to be used as a entry key or value, and Hashtable is not allowed.

HashMap hashtable contains method removed, changed to Containsvalue and ContainsKey. Because the contains method is easy to cause misunderstanding.

Hashtable inherits from the dictionary class, and HashMap is an implementation of the map interface introduced by Java1.2.

The biggest difference is that the Hashtable method is synchronize, and HashMap is not, when multiple threads access Hashtable, they do not need to synchronize their methods, and HashMap must provide it with external synchronization ( COLLECTIONS.SYNCHRONIZEDMAP).

Hashtable and HashMap use the same hash/rehash algorithms, so there's no big difference in performance.

HashMap and Hashtable differences in Java

Related Article

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.