[Java Essentials] Discussion on the traversal mechanism of HASHMAP and linkedhashmap elements

Source: Internet
Author: User

Map is a container for key-value pairs entry<k,v>, and the entry<k,v> of its internal key-value is always a sequential one.

This paper focuses on the traversal mechanism of HASHMAP and its sub-class Linkedhashmap, and summarizes the characteristics and application of the two.

CSDN-2014 Blog Star Poll

CSDN-2014 Blog Star selection begins, if you think my article is helpful to you, please click on the left column of the picture vote for me, your support is my knowledge to share a powerful power!



1.HASHMAP traversal mechanism

HashMap provides two interfaces that iterate through the entry<k,v> of its internal elements:

1. set<map.entry<k,v>> entryset () Returns a Set view of the mappings contained in this map.

2. set<k> keySet () returns a Set view of the keys contained in this map.

In fact, the second pretext represents the order of the key, which corresponds to the entry order returned by the first interface, that is to say: The two interfaces are the same as the order in which the elements of the HashMap are traversed. So, what is the order of HashMap traversing the internal entry<k,v>? To understand this problem, we must first know what the internal structure is.

The HASHMAP internal storage structure for key-value pairs uses the form of an array + linked list . Its structure is as follows:


HashMap the traversal order of the internal entry<k,v>:

on the entry[] table array, starting with index=0, and sequentially traversing the entry object on the linked list on table[i].


Since HashMap stores entry objects, it is based on the hash value of Key to determine which index value of the table array is stored on the linked list, so it is generally said: Use Hashmap.put (Key key,value value) The corresponding Entry<key,value> object is randomly assigned to a linked list of elements of a entry[] table array. In other words:

there is no relationship between the order of HashMap traversal entry objects and the order in which entry objects are stored.

However, we sometimes want to traverse the HASHMAP elements Entry order and the order of their storage, HashMap obviously can not meet the conditions. And Linkedhashmap can meet this need.


2. Traversal mechanism of Linkedhashmap

Linkedhashmap is a subclass of HashMap, which enables the storage order of entry within the container and the traversal order of the entry to be consistent.

To achieve this, Linkedhashmap internally uses a entry type of doubly linked list, which records the order in which the entry is stored using this doubly linked list . When the map needs to be traversed, it is actually traversing the doubly linked list.

The Linkedhashmap.entry class used internally by Linkedhashmap inherits from the Map.ent Ry class, On top of it, two fields of the Linkedhashmap.entry type are added to refer to the entry in the doubly linked list before the entry object and the entry object behind it.

Its interior is based on the Map.entry class, adding two references to the Entry type: Before,after. Linkedhashmap uses a doubly-connected table to string up all the entry inside it.



we will use the following example to understand how the internal doubly linked list is structured:

        Linkedhashmap Linkedhashmap = new Linkedhashmap ();        Linkedhashmap.put ("Name", "Louis");        Linkedhashmap.put ("Age", "the");        Linkedhashmap.put ("Sex", "male");

In addition to placing the corresponding entry object in the array list represented by the entry[] table, the code above will also add the entry object to its internally maintained doubly linked list. The corresponding Linkedhashmap internal bidirectional link list changes as follows:


Strategies for traversing the LINKEDHASHMAP:

start with the entry object that Header.after points to, and then go through the list until a entry.after = = header completes the traversal.


Thus, it is guaranteed to traverse the order of elements within the LINKEDHASHMAP, which is the order in which entry is inserted into Linkedhashmap.

Traversing the output of the Linkedhashmap defined in the above code will find that the order of traversal is exactly the same as the order in which it was inserted:

        Iterator<map.entry> iterator= Linkedhashmap.entryset (). Iterator ();        while (Iterator.hasnext ())        {            Map.entry Entry = Iterator.next ();            System.out.println (Entry.getkey () + ":" +entry.getvalue ());        
result output:



The way to traverse according to the order in which entry<k,v> inserts Linkedhashmap is called: traversing in the order of insertion .

In addition, LINKEDHASHMAP supports a traversal order calledget Read order .

If this get read traversal sequence of Linkedhashmap is turned on, then when we raise the Get (key) method in Linkedhashmap, it causes the entry of the internal key to move to the end of the doubly linked list in the bidirectional list.

For example, if the current linkedhashmap internal doubly linked list is as follows:

The relevant code is as follows:

        By default, the traversal mode of LINKEDHASHMAP is insert mode, and if you want to explicitly specify a get read mode, set the        parameter of//its constructor to true, (false means insert mode)        Linkedhashmap Linkedhashmap = new Linkedhashmap ((float) 0.75,true);        Linkedhashmap.put ("Name", "Louis");        Linkedhashmap.put ("Age", "the");        Linkedhashmap.put ("Sex", "male");        Linkedhashmap.get ("name");//get () method call, which causes the corresponding Entry to move to the last position of the doubly linked list        iterator<map.entry> iterator= Linkedhashmap.entryset (). iterator ();        while (Iterator.hasnext ())        {            Map.entry Entry = Iterator.next ();            System.out.println (Entry.getkey () + ":" +entry.getvalue ());        



3. Summary

1.HashMap the order in which elements are traversed is independent of the order in which entry is inserted, while Linkedhashmap's traversal order of elements can be consistent with the order in which entry<k,v> is inserted.

2. When Linkedhashmap is in get get sequential traversal mode, when the Get () operation is performed, the corresponding entry<k,v> is moved to the last position of the traversal.

3.LinkedHashMap is in the sequential traversal mode, if the newly inserted <key,value> corresponding key already exists, the position of the corresponding entry in the traversal order will not change.

4. In addition to the traversal order, other features HashMap and Linkedhashmap are basically the same.










[Java Essentials] Discussion on the traversal mechanism of HASHMAP and linkedhashmap elements

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.