The difference between Java Collection Framework 12--hashmap and Hashtable

Source: Internet
Author: User

We've already learned some of the map's contents, mainly HashMap and Hashtable, and we'll look at the similarities and differences between them in this section.

1. Similarities of HashMap and Hashtable

HashMap and Hashtable are both hash lists that store "key-value pairs," and are all implemented using the Zipper method. The idea of storage is that each element of an array is a entry through a table array, and a entry is a single list, entry each node in the linked list holds key-value data.

HashMap and Hashtable the same point basically nothing to study, we are more concerned about their differences,

2. Different points of HashMap and Hashtable

Analysis of different points, we also partially combined with the previous analysis of the source code, so more intuitive.

1) Different ways of inheriting

HashMap inherits and Abstractmap, and implements the map, cloneable and java.io.Serializable interfaces.

Hashtable inherits and Dictionary, and implements the map, cloneable and java.io.Serializable interfaces.

Dictionary is an abstract class that inherits directly from the object class and does not implement any interfaces. Dictionary is JDK1.0 introduced, although also supports the addition of key-value pairs, to obtain the basic operations such as value, but its API is less than map, and dictionary motion is through the enumeration to traverse, map is through the iterator to traverse. However, since Hashtable also implements the map interface, it also supports iterator traversal, which is explained later.

2) different thread safety

the HashMap method is non-synchronous , and to use HashMap under multithreading requires additional synchronization. For HASHMAP processing You can use the Synchronizedmap static method provided by the collections class, or use the Java.util.concurrent class in the Concurrenthashmap package provided directly after JDK5.0.

Hashtable almost all methods are synchronous , preceded by the Synchronized keyword, which supports multithreading.

3) The handling of null values is different

both the HashMap key and value can be null.

the Hashtable key and value are not nullable.

We can combine the two to add Key-value method to see:

HashMap add Key-value to the source public V put (K key, V value) {if (table = = empty_table) {//If the hash table is not initialized (table is empty) inflatetable (thres Hold); With the construction of the threshold (in fact, the initial capacity) extension table}//if key==null, the value is added to the location of table[0]//The position will always have only one value, the new incoming value will overwrite the old valueif (key = = NULL ) return Putfornullkey (value); int hash = hash (key); Calculates the hash value by the key value int i = indexfor (hash, table.length); Searches the index of the specified hash in the table//loops through the Entry array, and replaces the old valuefor (entry<k,v> e = table[i] with the new value if the key pair already exists: E! = null; e = E . Next) {Object k;if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))) {V OldValue = E.value;e.value = Valu E;e.recordaccess (this); return oldValue; and return the old value}}modcount++;//if the corresponding key is not found in table[i], then add this entryaddentry (hash, key, value, I) directly to the linked list in that location; return null;} Hashtable add Key-value source public synchronized v put (K key, v value) {    //ensure value is not empty      if (value = = null) {        throw New NullPointerException ();    } & nbsp  entry tab[]= table;    int hash = hash (key); Computes the hash value if key is null throws an exception     int index = (hash & 0x7FFFFFFF)% Tab.length; Computes the index in the array based on the hash value     for (entry<k,v> e = Tab[index]; E! = null; e = e.next) {    &nbs p;   if ((E.hash = = hash) && e.key.equals (key)) {//if the corresponding key already exists              v old = e.value;            e.value = value; Replace the original value            return old;        }    }    //Otherwise add a new entry    modCount++;    if ( Count >= threshold) {//Determine if the number of entry in the array has reached the threshold         rehash ();//If reached, expand          tab = table;        hash = hash (key); Recalculate hash values         index = (Hash & 0x7FFFFFFF)% Tab.length; Recalculate indexes in the new array     }    //create a new entry    Entry<K,V> e = Tab[index ];    //to the corresponding position, and next to the original position of the Entry, so it is connected with the original     tab[index] = new Entry<> ( Hash, key, value, E);    count++;    return null;}
As can be seen from the above code, Hashtable's key and value cannot be null, otherwise an exception is thrown, and the exception is nullpointerexception. Both the HashMap key and value can be null, and when key is NULL, HASHMAP inserts it into the table[0] position, and the location of Table[0] only holds a value that is null for the key.

4) Supported traversal types are different

HashMap only supports iterator traversal .

Hashtable supports iterator and enumeration two ways of traversing .

5) Different initial capacity and expansion mode

the default capacity of the HashMap is twice times the capacity of the original, when expanding;

the default capacity of the Hashtable is one, and the capacity is changed to twice timesthe original +1.

6) The hash value algorithm for adding key-value is different

HashMap When adding elements, a custom hashing algorithm is used ;

Hashtable is a hashcode () that uses key directly. Let's look at the source code:

static int hash (int h) {    h ^= (H >>> a) ^ (h >>> N);    Return h ^ (H >>> 7) ^ (H >>> 4);} HashMap Add public V put (K key, V value) {    //omit code    ... int hash = hash (Key.hashcode ());    Omit code ...}    Hashtable add public synchronized v put (K key, V value) {//Omit code ... int hash = Key.hashcode (); Omit code ...}

7) Some APIs are different

HashMap does not support the contains (Object value) method, and does not override the ToString () method;

Hashtable supports the contains (Object value) method and overrides the ToString () method.

The above is the main difference between the two, if there are additions or errors, welcome to the message ~

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----More articles please see: http://blog.csdn.net/eson_15

The difference between Java Collection Framework 12--hashmap and 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.