Java Improvement Chapter (33)-----Map Summary

Source: Internet
Author: User

In front of the LZ specifically introduced the HashMap, HashTable, TreeMap implementation method, from the data structure, implementation principle, source code analysis three aspects of the elaboration, the three classes should have a clearer understanding of the following LZ on the map to do a simple summary.

Recommended Reading:

Java Improvement Chapter (two or three)-–hashmap

Java Improvement Chapter (25)-–hashtable

Java Improvement (26)-----hashcode

Java Improvement Chapter (27)-–treemap

I. Overview of the map

First look at the structure of the map


Map: The abstract interface of the "key value" pair map. The map does not contain repeated keys, and a key corresponds to a value.

SortedMap: An ordered key-value pair interface that inherits the map interface.

Navigablemap: Inherits SortedMap, with an interface that returns the navigation method closest to a match for a given search target.

Abstractmap: Most of the function interfaces in map are implemented.

It reduces the repeated encoding of the "Map implementation class".

Dictionary: Abstract Parent class for a class that can map keys to corresponding values.

is now replaced by the map interface.

TreeMap: Ordered hash list, implements SORTEDMAP interface, bottom layer through red black tree realization.

HashMap: is a hash table based on the "zipper method" implementation.

The underlying is implemented with an array + linked list.

Weakhashmap: A hash table based on the "zipper Method".

HashTable: A hash table based on the "zipper Method".

Summary For example the following:


The difference between them:


Two, internal hash: hash mapping technology

Almost all universal maps use hash mapping techniques. We have to know something about our procedural apes.

The hash mapping technique is a very easy technique for mapping elements to arrays.

Because the hash map uses array results, there must be an indexing mechanism that determines the random key access array, which can provide an integer that is less than the size of the array. We call this mechanism a hash function.

In Java we don't have to worry about looking for such integers, because every object must have a Hashcode method that returns an integer value, and all we have to do is convert it to an integer and then divide that value by the size of the array.

For example, the following:

int hashValue = Maths.abs (Obj.hashcode ())% size;
The following are HashMap, Hashtable:

----------HashMap------------//Calculate hash value static int hash (int h) {    h ^= (H >>>) ^ (h >>> N);    Return h ^ (H >>> 7) ^ (H >>> 4);} Calculates the index position of the key in static int indexfor (int h, int length) {        return H & (length-1);} -----HashTable--------------int index = (hash & 0x7FFFFFFF)% Tab.length;     Confirm the index position of the key

The index of the position represents the position of the node in the array. Is the basic diagram of the hash map:


In this figure, the 1-4 step is to find the element in the array position, and the 5-8 step is to insert the element into the array. In the process of inserting a little bit of frustration. In many Ken can exist multiple elements of their hash value is the same. This will give you the same index position, which means that multiple elements are mapped to the same location, which we call "collisions".

The way to resolve conflicts is to insert a list of links at the index location. and simply add elements to this list of links. Of course it is not a simple insert, the process steps in HashMap are as follows: Gets the list of indexed locations. Assuming that the linked list is null, the element is inserted directly, otherwise the element is saved in the chain header (the first saved element is placed at the end of the chain) if there is a key that is the same as the key, if it is present and the value of the original key is overwritten, and the old value is returned. The following is the put method of HashMap, which shows the location of the computed index in detail. The entire process of inserting an element into the appropriate location:

Public V put (K key, V value) {        ///When key is NULL, call the Putfornullkey method, save null with table in the first position, this is the reason that HashMap agrees to null        if (key = = NULL)            return Putfornullkey (value);        Computes the hash value of the key        int hash = hash (Key.hashcode ());                         Computes the position of the key hash value in the table array        int i = indexfor (hash, table.length);                    Starting from I iteration e, infer if there is the same key for        (entry<k, v> e = table[i]; E! = null; e = e.next) {            Object K;            Infer if there is a hash value on the chain (same as key)            //If the same is true, overwrite value directly. Returns the old value            if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))) {                V oldValue = e.value;    Old value = new value                e.value = value;                E.recordaccess (this);                return oldValue;     return old value            }        }        //Number of changes added 1        modcount++;        Add key and value to the I position        addentry (hash, key, value, I);        return null;    }

The Put method of HashMap shows the basic idea of hash mapping, and in fact assumes that we look at other maps. found that the principle is almost the same!


third, map optimization

First, let's assume that the size of the internal array of the hash map is only 1. All of the elements will map that position (0) to form a longer linked list. Because we update, access to the list to be a linear search. This is bound to reduce efficiency. Let's assume that there is a large array, and that there is only one element at each location list. The object is obtained by calculating its index value at the time of the interview, which, while improving the efficiency of our search, wastes the control. Admittedly, although both approaches are extreme, it gives us an idea of optimization: using a larger array allows the elements to be evenly distributed. Two of the maps have effects on their efficiency, one is the container's initialization size, and the second is the load factor.

3.1, adjust the implementation size

in the hash mapping table. Each location in an internal array is called a bucket. While the number of buckets available (that is, the size of the internal array) is called capacity (capacity), we design the map to resize itself so that the map object can handle the arbitrary number of elements efficiently.

We know that when the elements in the map reach a certain amount, the size of the container itself is adjusted, but the size of the process is much more expensive.

resizing requires inserting all of the original elements into the new array. We know index = hash (key)% length.

This may cause the previously conflicting keys not to be in conflict. Non-conflicting keys are now conflicting. Another calculation, adjustment, and insertion of the process cost is very large, inefficient.

So, Suppose we start to know the expected size of the map, and if the map is large enough, it can be greatly reduced or even not required to resize again, which is likely to be faster.

Here is the process of hashmap resizing the container, and we can see the complexity of its expansion process through the following code:

void Resize (int newcapacity) {entry[] oldtable = table;    Original container int oldcapacity = oldtable.length; Original container size if (oldcapacity = = maximum_capacity) {//whether the maximum value is exceeded: 1073741824 threshold = Integer.max                _value;            Return                }//new array: Size oldcapacity * 2 entry[] newtable = new Entry[newcapacity];            Transfer (newtable, inithashseedasneeded (newcapacity));           Table = newtable;             /* * Once again calculated threshold = newcapacity * loadfactor > maximum_capacity + 1? * Newcapacity * loadfactor:maximum_capacity + 1 */threshold = (int) MATH.MI           N (newcapacity * loadfactor, maximum_capacity + 1); }//Insert element into new array void transfer (entry[] newtable, Boolean rehash) {int newcapacity = NewTab            Le.length;                  for (entry<k,v> e:table) {while (null! = e) {  Entry<k,v> next = E.next;                    if (rehash) {E.hash = NULL = = E.key? 0:hash (E.key);                    } int i = Indexfor (E.hash, newcapacity);                    E.next = Newtable[i];                    Newtable[i] = e;                e = next; }            }        }

3.2. Load factor

to confirm when the map container needs to be adjusted, Map uses an additional number of parameters and roughly calculates the density of the storage container. Before the map is resized, use a "load factor" to indicate the "load" that the map will assume, that is, its load level, and the map will expand when the number of elements in the container reaches this "load". The relationships between load factors, capacity, and map size are as follows: Load factor * capacity > Map Size-----> Adjust map size.

For example: Suppose the load factor size is 0.75 (the default value of HashMap), the default capacity is 11, then 11 * 0.75 = 8.25 = 8. So when we insert a eighth element into our container, the map resizes.

The load factor itself is a tradeoff between the control and the time. When I use a smaller load factor. Although the possibility of conflict has been reduced. Reduces the length of a single linked list, speeding up access and updates. But it takes up a lot of other controls. So that most of the controls in the array are not exploited and the element distribution is sparse, at the same time because the map is frequently resized. Performance may be reduced.

However, assuming that the load factor is too large, it will make the element distribution is relatively compact, resulting in increased likelihood of conflict, so that access to ask, update slower. So we generally recommend not changing the value of the load factor, using the default value of 0.75.

finally

Recommended reading:

Java Improvement Chapter (two or three)-–hashmap

Java Improvement Chapter (25)-–hashtable

Java Improvement (26)-----hashcode

Java Improvement Chapter (27)-–treemap

-----Original:

p=1212 "href=" http://cmsblogs.com/?p=1212 ">http://cmsblogs.com/?p=1212, please respect the author's hard work results, reproduced the source of the explanation.

-----personal website: http://cmsblogs.com

Java Improvement Chapter (33)-----Map Summary

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.