Java notes four HashMap parsing __java

Source: Internet
Author: User
Tags rehash concurrentmodificationexception

http://tangmingjie2009.iteye.com/blog/1698595

http://blog.csdn.net/itm_hadf/article/details/7497462

Ava.util class Hashmap<k,v>
Java.lang.Object
Java.util.abstractmap<k,v>
Java.util.hashmap<k,v>
Type parameters:
K-Types of keys maintained by this mapping
V-the type of the mapped value
All implemented interfaces:
Serializable, Cloneable, map<k,v>
Child classes are directly known:
Linkedhashmap, Printerstatereasons

--------------------------------------------------------------------------------

public class Hashmap<k,v>extends abstractmap<k,v>implements Map<k,v>, cloneable, Serializable the implementation of MAP interface based on hash table.

Features:
(1) This implementation provides all optional mapping operations and allows NULL values and NULL keys to be used.
(The HashMap class is roughly the same as Hashtable, except for asynchronous and null-enabled use.) )
(2) This class does not guarantee the order of mappings, especially if it does not guarantee that the order is immutable.
(3) This implementation assumes that the hash function distributes the elements appropriately between the buckets, providing stable performance for basic operations (get and put).





The time required to iterate the collection view is proportional to the number of HASHMAP instances and their size (number of key-value mapping relationships).

So, if iterative performance is important, do not set the initial capacity too high (or set the load factor too low).

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
(1) The capacity is the number of buckets in the hash table, and the initial capacity is just the capacity of the hashtable at the time of creation.
(2) load factor is a kind of scale that the hash table can reach more than full before its capacity automatically increases.

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the Hashtable is rehash (that is, the internal data structure is rebuilt), so the Hashtable will have about twice times the number of buckets.

Typically, the default load factor (. 75) seeks a tradeoff between time and space costs.
The high load factor, while reducing the space overhead, also increases the cost of the query (which is reflected in the operations of most HASHMAP classes, including get and put operations).
The initial capacity should be set to take into account the number of entries and their load factors required in the mapping in order to minimize the number of rehash operations.


If the initial capacity is greater than the maximum number of entries divided by the load factor, the rehash operation does not occur.


If many mapping relationships are to be stored in the HashMap instance, it will be more efficient to store the mapping relationship by using a large enough initial capacity to create it, relative to performing an automated rehash operation on demand to increase the capacity of the table.

Note that this implementation is not synchronized. If more than one thread accesses a hash map at the same time, and at least one of the threads modifies the mapping from the structure, it must maintain an external synchronization.
(Structural modification means any action that adds or deletes one or more mapping relationships; changing only the value associated with the key that the instance already contains is not a structural modification.) )
This is typically done by synchronizing the objects that naturally encapsulate the mapping.



If no such object exists, you should use the Collections.synchronizedmap method to "wrap" the mapping.
It is best to do this at creation time to prevent unexpected, asynchronous access to the mappings, as follows:

Map m = collections.synchronizedmap (new HashMap (...));

The iterators returned by all of the "collection View methods" of this class are fast failures:
After the iterator is created, if you modify the mappings from the structure, unless you pass the Remove method of the iterator itself,
Any other time any way to modify, the iterator will throw the concurrentmodificationexception.


Therefore, in the face of concurrent modifications, the iterator will soon fail completely, without risking any uncertain behavior at a future time of uncertainty.

Note that the rapid failure behavior of the iterator is not guaranteed, and in general, there is no firm guarantee when there are asynchronous concurrent modifications.
The fast fail iterator tries its best to throw concurrentmodificationexception.

Therefore, it is wrong to write a program that relies on this exception, and the correct approach is that the rapid failure behavior of the iterator should be used only for detecting program errors.

This class is a member of the Java collections Framework.

(1)
ContainsKey
public boolean ContainsKey (Object key) returns True if this map contains a mapping relationship to the specified key.

Designated by:
ContainsKey in the interface map<k,v>
Covered:
ContainsKey in the class abstractmap<k,v>
Parameters:
Key-the key to test whether it exists in this map
Return:
Returns TRUE if this map contains a mapping relationship to the specified key.

(2)
Keyset
Public set<k> Keyset () returns the Set view of the keys contained in this map. The set is supported by mappings, so changes to the mappings are reflected in the set and vice versa. If the mappings are modified while the set is being iterated (except through its own remove operation), the iteration result is indeterminate. The set supports the removal of elements, which can be removed from the mapping by Iterator.remove, Set.remove, RemoveAll, Retainall, and clear operations. It does not support add or addall operations.




Designated by:
Keyset in the interface map<k,v>
Covered:
Keyset in the class abstractmap<k,v>
Return:

The set view of the keys contained in this map is described in relation to set use. 】


Here is an example to illustrate the resolution:

[Java]  View plain copy print? public class hashmaptest {       public static void  main (String[] args)  {                      hashmap<string,string> keysetmap = new  HashMap<String,String> ();           HashMap< String,string> entrysetmap=new hashmap<string,string> ();                       for  (int i = 0;i<1000;i++)  {                keysetmap.put ("" "+i, " keyset ");           }            for (int i=0;i<1000;i++) {   &Nbsp;           entrysetmap.put ("" "+i," EntrySet ");            }                       long startTimeOne =  System.currenttimemillis ();           <strong><span  style= "COLOR: #ff0000;" >iterator<string> keysetiterator = keysetmap.keyset () Iterator ();            while  (Keysetiterator.hasnext ())  {                system.out.println (</span><span  style= "COLOR: #000099;" >keysetmap.get (Keysetiterator.next ()) </span><span style= "color: #ff0000;" >);           }</span></strong> &nbsp &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Keyset traversal time-------------------------------: "+ (System.currenttimemillis ()-starttimeone));                       long starttimetwo=system.currenttimemillis ();            Iterator<Entry<String,String>>  Entrysetiterator=entrysetmap.entryset () iterator ();            while (Entrysetiterator.hasnext ()) {                entry<string,string> entry=entrysetiterator.next ();                system.out.println (Entry.getvalue ());            }            System.out.println ("EntrySet traversal Time---------------------------: "+ (System.currenttimemillis ()-starttimetwo));        }  }  
By running the test multiple times, the EntrySet traversal time is much shorter than the keyset traversal time, and the performance of the EntrySet mode is usually one times higher than that of the keyset method.

three. why.




by looking at the source code discovery, invoking the Keysetmap.keyset () method generates a Keyiterator iterator,
Its next () method returns only its key value, and then obtains its value value in Keysetmap via the key value, code such as: Keysetmap.get (Keysetiterator.next ())

The call to the Entrysetmap.entryset () method generates a Entryiterator iterator whose next () method returns an instance of a entry object that contains the key value and value.
If you traverse hashmap with only its key value, the traversal in both ways should be the same in performance.

But at the same time take the key value and value values, keyset way than the EntrySet way to traverse a table, at this time keyset way performance is worse.


HashMap Depth Analysis (reprint)


Java.util.HashMap is a very common class, the previous period of time the company system due to improper use of hashmap, resulting in the CPU hundred percent,
Using HashMap without synchronization in a concurrent environment may cause a dead loop, as the Sun's official website has already elaborated on, which is not a bug.


Data structure of HashMap
HashMap mainly use arrays to store data, we all know that it will hash the key, the HA operation will have a duplicate hash value, for the hash value of the conflict, HashMap using the linked list to solve.


In HashMap, there is a property declaration that says:
Transient entry[] table;
Entry is the class that the HashMap uses to store data, which has the following attributes
Final K Key;
V value;
final int hash;
Entry<k,v> Next;

Have you seen next? Next is the existence of a hash conflict. For example, by hashing, a new element should be in the 10th position of the array, but the 10th position already has entry, so well, add the new element to the 10th position and assign the original entry of the 10th position to the next property of the current new entry. The array stores a list of linked lists that are designed to solve the Greek conflict, and this should be noted.


Several key attributes
An array of stored data
Transient entry[] table; It's already been mentioned.
Default capacity
static final int default_initial_capacity = 16;
Maximum capacity
static final int maximum_capacity = 1 << 30;
The default load factor, load factor is a ratio, when the HashMap data size >= capacity * load factor, HASHMAP will capacity expansion
Static final float default_load_factor = 0.75f;
When the actual data size exceeds threshold, HASHMAP will enlarge capacity, threshold= capacity * load factor
int threshold;
Load factor
Final float Loadfactor;


The initial process of HashMap
Constructor 1:

[Java] view plain copy print?

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.