Java Collection Class Linkedhashmap of learning Notes

Source: Internet
Author: User

1. Brief introduction

Linkedhashmap is a subclass of HashMap, their biggest difference is that HashMap internally maintains a one-way list of linked lists, while Linkedhashmap internally maintains a two-way list of linked arrays. HashMap are unordered, linkedhashmap can be sorted according to the order of access or insertion order (by default, according to the order of insertion, when the set Accessorder is true, it is sorted in the order of access), when sorted in order of access, Each time a get or put operation is put, the node is placed at the end of the list

2. Realization 1, data structure:

Linkedhashmap is a subclass of HashMap, and its interior is also the data stored using the HashMap defined list array. It is only used in HashMap to list node<k,v> as each node, while Linkedhashmap uses a doubly linked list with integrated hashmap.node<k,v> entry<k,v> As each node,entry<k,v> on the basis of node<k,v> added entry<k,v> before, after two properties, associating the front and back elements in the array, Such implementations also provide the possibility of LINKEDHASHMAP based on the order of insertion or the order of access

2. Construction Method:

Linkedhashmap is a subclass of HashMap, which provides five ways to construct

  PublicLinkedhashmap (intInitialcapacity,floatloadfactor) {        Super(initialcapacity, loadfactor); Accessorder=false; } PublicLinkedhashmap (intinitialcapacity) {        Super(initialcapacity); Accessorder=false; } PublicLinkedhashmap () {Super(); Accessorder=false; } PublicLinkedhashmap (map<?extendsK?extendsV>m) {Super(); Accessorder=false; Putmapentries (M,false); } PublicLinkedhashmap (intinitialcapacity,floatLoadfactor,BooleanAccessorder) {        Super(initialcapacity, loadfactor);  This. Accessorder =Accessorder; }

From the above we can see that the first four of the construction method is the default Accessorder=false, that is, by looking for the insertion order, the fifth construction method we can define the value of Accessorder, when True, the description is in order of access, Each time a put or get operation moves the element to the end of the list

3. Linkedhashmap operation

Because Linkedhashmap inherits the HashMap class, and does not rewrite put,get, and so on, so here for the linkedhashmap of the underlying operation of the source code is no longer analyzed, interested can refer to the previous article about HashMap study notes. Here's a look at the Removeeldestentry (map.entry<k,v> eldest) method provided by Linkedhashmap

    

/**     * Returns <tt>true</tt> If this map should remove its eldest entry. * This method was invoked by <tt>put</tt> and <tt>putAll</tt> after * inserting a new entry int  o the map.  IT provides the implementor * with the opportunity-to-remove the eldest entry each time a new one * is added. This is useful if the map represents a cache:it allows * the map to reduce memory consumption by deleting stale entri     Es. * * <p>sample Use:this Override would allow the "map to grow Up" to "entries" and then delete the eldest E     Ntry each time a new entry was * added, maintaining a steady state of entries.     * <pre> * private static final int max_entries = 100; * * Protected Boolean removeeldestentry (Map.entry eldest) {* Return size () &gt;     Max_entries; *} * </pre> * * <p>this method typically does not modify the map in any method, * instead AL LOwing the map to modify itself as directed by its * return value. It <i>is</i> permitted for this method to modify * The map directly, and if it does so, it &LT;I&GT;MUST&L t;/i> return * <tt>false</tt> (indicating that the map should no attempt any * further Modificatio n). The effects of returning <tt>true</tt> * After modifying the map from within this method is Unspecif     Ied. * * <p>this implementation merely returns <tt>false</tt> (so, this * map acts like a normal     Map-the eldest element is never removed).  *     *@parameldest the least recently inserted entry in the map, or if * It's an access-ordered map, the LEAs  T recently accessed * entry.  This was the entry that would be removed it this * method returns <TT>TRUE</TT>. If the map is empty prior * to the <tt>put</tt> or <tt>putAll</tt> invocation Resul Ting * Invocation, this is the entry that is just * inserted;     In other words, if the map contains a single * entry, the eldest entry is also the newest. * @return<tt>true</tt> If the eldest entry should is removed * from the map; <tt>false</t     T> if it should be retained. */    protected BooleanRemoveeldestentry (map.entry<k,v>eldest) {        return false; }

This method is to determine if you need to delete the oldest element in Linkedhashmap, which is false by default. When we need to use HashMap to do some data cache, the data may be used one or two times after the loss of value, in addition we do not want to see the cached map unlimited growth and do not want to manually maintain the map. At this point we can use Linkedhashmap to complete this function;

 Public classDemo {Static classMymap<k,v>extendslinkedhashmap<k,v>{//define a class that inherits Linkedhashmap and override the Removeeldestentry method        intsize;  PublicMyMap (intSize) {//provides only one parameter constructor to set the size of the map            /** This is called the Linkedhashmap linkedhashmap (int initialcapacity,boolean accessorder) * Construction method, set to sort by access order */            Super(16,0.75f,true);  This. Size =size; } @Overrideprotected BooleanRemoveeldestentry (Entry<k, v>eldest) {            //TODO auto-generated Method Stub            return  This. Size<size ();//sets the oldest element to be deleted when the element stored in the map exceeds the size set by Mymap        }            }     Public Static voidMain (string[] args) {Map<String,String> map =NewMymap<string,string> (5);  for(inti = 0; I < 10; i++) {Map.put (i+ "", i+ ""); System.out.print (i+ "=" +map.size () + "\ T");        } System.out.println (); //traverse the map to see the elements insideMap.foreach ((k,v){System.out.println ("K=" +k);                }); //at this point, access the elements inside, then observe the order of the traversalMap.get ("6"); Map.get ("8")); System.out.println ("========================"); Map.foreach ((k,v)-{System.out.println ("K=" +k);    }); }}

Printed results:
  

0=1 1=2 2=3 3=4 4=5 5=5 6=5 7=5 8=5 9=5
K=5
K=6
K=7
K=8
K=9
========================
K=5
K=7
K=9
K=6
K=8

  

Summarize:

After studying Linkedhashmap and HashMap, we will find that the two collection classes are very similar, both of which hold data through an internal array, but each element in the HashMap array is a one-way list. Points to an element that generates a hash conflict and has the same hash value as itself, so the hashmap can only be unordered. Each element in the Linkedhashmap array is a doubly linked list that points to the next position that has the same hash value as itself when the hash conflict is generated, and also specifies its previous and next elements (which can be the previous next in the insert order, You can also try to access the previous next in the order, which provides the possibility of LINKEDHASHMAP implementation

Java Collection Class Linkedhashmap of learning Notes

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.