Hashtable, HashMap, Linkedhashmap in Java

Source: Internet
Author: User

In front of the list of arrlist and linkedlist the difference is not below, the time to summarize some of the map of the class.

I. Overview

First of all, the introduction of three map (TreeMap is very special, temporarily ignored)

1, Hashtable: Array + single-linked list structure, thread safety (operation locking), unordered,

2, HashMap: Array + single-linked list structure, thread unsafe, unordered,

3, Linkedhashmap: Inherit the HashMap, array + single-linked list structure, thread unsafe, orderly (1, insert order 2, LRU: least recent access order [with two-way list storage order])

The above is the general characteristics of the three map, then how these features are implemented, we can cut from several aspects of the source code analysis of three different: constructors, put method, get method,

Second, the bottom structure

1, HashTable: When storing a value, the key is calculated according to the table array in the lower corner subscript I, if table[i] is empty, directly into the generated entry, if not empty from the entry head of the location, if the key is the same, the value is overwritten, If there is no entry of the same key, the newly generated entry is placed in the header of the lower corner of the array;

* Hashtable is used to store data in an array, the elements in the array are entry, as described below. */ Private transientEntry<k,v>[] table; /*** The element in the Hashtable array is entry, which is the structure of a key and value (method omitted in class)*/ Private Static classEntry<k,v>ImplementsMap.entry<k,v> {
The hash value of the current entryintHash;
Key value of the current entryFinalK Key;
The value of the current enry, V values;
The next Entry of the current Entry (as can be seen here is a single-linked list) Entry<K,V>Next;

2, HashMap: With the Hashtable exactly the same bottom structure

    /*** An empty entry array*/    Static Finalentry<?,? >[] empty_table = {}; /*** As with Hashtable, table arrays, which hold entry objects, differ only by initializing them directly to an empty array*/    transiententry<k,v>[] Table = (entry<k,v>[]) empty_table; The entry object is exactly the same as entry .Static classEntry<k,v>ImplementsMap.entry<k,v> {        FinalK Key;        V value; Entry<K,V>Next; intHash;    }

3, Linkedhashmap: The following code can be seen, Linkedhashmap inherited the HashMap, on the basis of HashMap added hear doubly linked list and entry in the front and back tags

 Public classLinkedhashmap<k,v>extendsHashmap<k,v>ImplementsMap<k,v>{      /*** The class shows that HashMap is inherited, so the underlying data grid uses the HashMap table directly.
This hear is a linked list, head for the list of heads, followed by*/ Private transientEntry<k,v>header; /*** Accessorder attribute: Used to mark whether the hear doubly linked list is to eradicate the LRU sort or the order of insertions */ Private Final BooleanAccessorder; }
/**      * entry in Linkedhashmap inherits Enry     */    privatestatic in HashMap Classextends hashmap.entry<k,v> {        //  Two more properties: Entry before and after Entry, This is the        entry<k,v> before for head , after;     }

Iii. constructors (only for large processes)

1, Hashtable

* Most commonly used constructors, here called the This constructor, passed two parameters 11 and 0.75, the following describes the significance of the parameter*/     PublicHashtable () { This(One, 0.75f); }    /*** As you can see, the first parameter is the initial capacity is small, here the default is set to 11, the second parameter is the expansion factor, by default when the container is 75 used when the expansion*/     PublicHashtable (intInitialcapacity,floatloadfactor) {
Check capacity setting sizeif(Initialcapacity < 0) Throw NewIllegalArgumentException ("Illegal capacity:" +initialcapacity);
Check load factor sizeif(loadfactor <= 0 | |Float.isnan (loadfactor))Throw NewIllegalArgumentException ("Illegal Load:" +loadfactor); if(initialcapacity==0) initialcapacity= 1; This. Loadfactor =Loadfactor;
Initialize the entry array based on the initial capacity size (remember that the Hashtable is initialized when the attribute is defined above) Table=NewEntry[initialcapacity];
Calculate the critical value of expansion: Total capacity * load factor threshold= (int) math.min (initialcapacity * loadfactor, max_array_size + 1);
Calculates the Hashseed parameter, which is used to calculate the hash value of the element key inithashseedasneeded (initialcapacity); }

can see:

1, hashtable default initialization size is 11, the default expansion load factor is 0.75

2. The Hashtable array container is completed at initialization time

2, HashMap

    /*** Code optimization is done here, using constants, passing in two parameters: 16 and 0.75*/     PublicHashMap () { This(default_initial_capacity, default_load_factor); }    /*** Initial capacity is not the same as Hashtable, here is 16, loading factor is 0.75 * capacity and load factor.*/     PublicHashMap (intInitialcapacity,floatloadfactor) {
Check initial capacityif(Initialcapacity < 0) Throw NewIllegalArgumentException ("Illegal initial capacity:" +initialcapacity); if(Initialcapacity >maximum_capacity) initialcapacity=maximum_capacity; if(loadfactor <= 0 | |Float.isnan (loadfactor))Throw NewIllegalArgumentException ("Illegal load factor:" +Loadfactor);
Set load factor and initial capacity value This. Loadfactor =Loadfactor; Threshold=initialcapacity;
This method is empty, you can see that the HashMap just set the initial value, and did not calculate the same as Hashtable, to the current position table array or an empty array
(In fact, HashMap is the first time put into the element, only the capacity of the HashMap and other information to initialize, see below) init (); }

Here you can see what the HashMap constructor does:

1, HashMap container, default capacity 16, expansion load factor 0.75

2. The constructor only makes the parameter check and parameter setting, and does not set the table to the true size, nor does it calculate the capacity critical value of the expansion.

3, Linkedhashmap

    /**      * The constructor of the fully multiplexed HashMap. The Accessorder property is set to False by default: The Hear list is sorted     in order of insertion *      /Public Linkedhashmap () {         Super();         false ;    }

Linkedhashmap Nothing to say, exactly like HashMap, more than a head list of the sort settings.

Iv. Put method

1, Hashtable





Hashtable, HashMap, Linkedhashmap 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.