Java Source Beginner _linkedhashmap

Source: Internet
Author: User

I. Overview:

 Linkedhashmap is a subclass of HashMap, and its basic operation is the same as HashMap, and unlike it, it can be sorted in order of insertion. You can also sort by access order by specifying parameters in the constructor ( Linkedhashset cannot be sorted in order of access).

Two. How is linkedhashmap implemented in order of insertion?
Linkedhashmap a little bit in the entry inner class ... In fact, all elements of linkedhashmap can form a doubly linked list with header (entry object) as head. In HashMap there is a hook method init, called in the last line of the constructor, in the implementation of the HashMap, The Init method does not implement anything. While Linkedhashmap implements the Init method, the code for the Init method is as follows:

void init () {        newnull-null null)        ; = Header.after = header;    }

Linkedhashmap to the AddEntry method has also been modified, first it did not change the data structure of the array, at the time of placing an element, still the hash value of the element corresponding to the index of the reference point to the element, the element's next property to the previous reference to the element at the point of the index, The difference is that when inserting a new element, it also maintains the insertion of a doubly linked list data structure. First look at the data structure of the inner class entry:

Private Static classEntry<k,v>extendsHashmap.entry<k,v> {        //These two references illustrate that entry is connected by a doubly linked list.Entry<k,v>before, after; Entry (intHash, K key, V value, hashmap.entry<k,v>next) {            Super(hash, key, value, next); }        /*** Remove this entry from the doubly linked list*/        Private voidRemove () {Before.after=After ; After.before=before; }        /*** Add this entry to the front of the given parameter entry*/        Private voidAddbefore (entry<k,v>existingentry) { After=Existingentry; Before=Existingentry.before; Before.after= This; After.before= This; }        /*** This method is called when the support is sorted by the number of accesses. It is also defined in HashMap, but does not give a concrete method to implement in Linkedhashmap*/        voidRecordaccess (hashmap<k,v>m) {Linkedhashmap<K,V> lm = (linkedhashmap<k,v>) m; if(lm.accessorder) {Lm.modcount++;                Remove ();            Addbefore (Lm.header); }        }                voidRecordremoval (hashmap<k,v>m) {remove (); }    }

Then look at the AddEntry method and the Createentry method:

voidAddEntry (intHash, K key, V value,intBucketindex)        {Createentry (hash, key, value, Bucketindex); //in Linkedhashmap, the Removeeldestentry method always returns falseentry<k,v> eldest =Header.after; if(Removeeldestentry (eldest)) {Removeentryforkey (Eldest.key); } Else {            if(Size >=threshold) Resize (2 *table.length); }    }    voidCreateentry (intHash, K key, V value,intBucketindex) {Hashmap.entry<K,V> old =Table[bucketindex]; Entry<K,V> e =NewEntry<k,v>(hash, key, value, old); Table[bucketindex]=e; //maintaining the operation of a doubly linked listE.addbefore (header); Size++; }

It can be seen that the invocation of the Addbefore method implements the operation of maintaining a doubly linked list, and the following lists what happens internally when an element is inserted into a linkedhashmap without any elements:
1. First calculate the hash value of the key value pair. The index is computed based on the hash value.
2. Use the passed-in key value to create a entry object for new. Because the index is NULL, the reference at that index of the underlying array is pointed at the entry object
3. Insert the entry object in front of the header, Header.before the Entry,header.after is also the entry.
4. Increase size, if size>=threshold, increase the volume of the container.
When you continue adding elements, the newly added elements are added to the front of the header, and Header.after is always the first element added.
The following is an iterator defined by Linkedhashmap:

 Private Abstract classLinkedhashiterator<t>ImplementsIterator<t>{Entry<K,V> NextEntry =Header.after; Entry<K,V> lastreturned =NULL; intExpectedmodcount =Modcount;  Public BooleanHasnext () {returnNextEntry! =header; }     Public voidRemove () {if(lastreturned = =NULL)        Throw Newillegalstateexception (); if(Modcount! =expectedmodcount)Throw Newconcurrentmodificationexception (); Linkedhashmap. This. Remove (Lastreturned.key); lastreturned=NULL; Expectedmodcount=Modcount; } Entry<K,V>NextEntry () {if(Modcount! =expectedmodcount)Throw Newconcurrentmodificationexception (); if(NextEntry = =header)Throw Newnosuchelementexception (); Entry<K,V> E = lastreturned =NextEntry; NextEntry=E.after; returne; }    }

As you can see, the iterator starts from the header and calls Header.after to get the element. Until the pointer goes back to the header. Therefore, the iteration order of such a sub-sequence is ensured by the data structure of the internal doubly linked list, which is sorted by the insertion order.
three. How is linkedhashmap implemented in order of access?
in Linkedhashmap, there is a member variable Accessorder to determine whether to sort by access order. Accessorder can be specified by passing in the constructor with true, Must be sorted in order of access. The so-called order of access means that if a pair of key-value pairs are accessed, it is moved to the end of the current traversal order, so that the most infrequently accessed key-value pairs are in front.
in Linkedhashmap, by calling the Recordaccess method after get, you can sort by Access order:

 Public V get (Object key) {        Entry<K,V> e = (entry<k,v>) getentry (key);         if NULL )            returnnull;        E.recordaccess (this);         return e.value;    }

The Recordaccess method is implemented in the entry inner class, which is to remove the entry from the doubly linked list and rejoin the entry to the front of the header (the last traversal will be traversed) so that it is sorted by access order.

  

Java Source Beginner _linkedhashmap

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.