Java.util
Class hashmap<k,v>
Java.lang.Object
Java.util.abstractmap<k,v>
Java.util.hashmap<k,v>
Type parameter:
K-The type of key maintained by this mapping
V-the type of the mapped value
All implemented interfaces:
Serializable, Cloneable, map<k,v>
Directly known subclasses:
Linkedhashmap, Printerstatereasons
--------------------------------------------------------------------------------
public class Hashmap<k,v>extends abstractmap<k,v>implements Map<k,v>, cloneable, Serializable the implementation of the Map interface based on the hash table.
Features:
(1) This implementation provides all the optional mapping operations and allows NULL values and NULL keys to be used.
(The HashMap class is roughly the same as Hashtable except for non-synchronous and null-allowed use.) )
(2) This class does not guarantee the order of the mappings, in particular it does not guarantee that the order is immutable.
(3) This implementation assumes that the hash function distributes elements appropriately between buckets, providing stable performance for basic operations (get and put).
The time required to iterate the collection view is proportional to the capacity of the HashMap instance (the number of buckets) and its size (number of key-value mappings).
Therefore, if iteration 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) capacity is the number of buckets in the hash table, and the initial capacity is just the capacity at the time of creation of the Hashtable.
(2) The load factor is a scale in which a hash table can reach a full amount before its capacity increases automatically.
When the number of entries in the hash table exceeds the product of the load factor with the current capacity, the Hashtable is rehash (that is, rebuilding the internal data structure) so that the Hashtable will have about twice times the number of buckets.
Typically, the default load factor (. 75) seeks a tradeoff in time and space costs.
The high load factor, while reducing the space overhead, also increases the query cost (which is reflected in the operations of most HASHMAP classes, including get and put operations).
When setting the initial capacity, you should take into account the number of entries required in the mapping and their loading factors to minimize the number of rehash operations.
The rehash operation does not occur if the initial capacity is greater than the maximum number of entries divided by the load factor.
If many of the mapping relationships are to be stored in the HASHMAP instance, creating it with a large enough initial capacity will make it more efficient to store the mapping relationship relative to the automatic rehash operation on demand to increase the capacity of the table.
Note that this implementation is not synchronous. 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 remain externally synchronized.
(Structural modification is any action that adds or deletes one or more mapping relationships; changing only the values associated with the key that the instance already contains are not structural modifications.) )
This is typically done by synchronizing the objects that naturally encapsulate the mapping.
If such an object does not exist, you should use the Collections.synchronizedmap method to "wrap" the map.
It is a good idea to do this at creation time to prevent unintended non-synchronous access to the mappings, as follows:
Map m = collections.synchronizedmap (new HashMap (...));
The iterator returned by all such "collection View Methods" is a quick failure:
After the iterator is created, if the mapping is modified from the structure, unless it is passed through the Remove method of the iterator itself,
Any other change in any way at any time, the iterator will throw concurrentmodificationexception.
Therefore, in the face of concurrent modifications, the iterator will soon fail completely without risking any uncertain behavior at any time in the future.
Note that the fast failure behavior of iterators is not guaranteed and, in general, there is no firm guarantee that there is an asynchronous concurrent modification.
The fast-failing iterator does 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 fast failure behavior of the iterator should only be used to detect 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 for the specified key.
Designated by:
ContainsKey in the interface map<k,v>
Covered:
ContainsKey in the class abstractmap<k,v>
Parameters:
Key-to test whether it exists in this mapping
Return:
Returns TRUE if this map contains a mapping relationship for the specified key.
(2)
KeySet
Public set<k> KeySet () returns a Set view of the keys contained in this map. The set is supported by the mappings, so changes to the mappings are reflected in the set, and vice versa. If you modify the mapping while iterating over the set (except through the iterator's 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 "about set usage see below." 】
The following example demonstrates the parsing:
public class Hashmaptest {public static void main (string[] args) {hashmap<string,string> k Eysetmap = 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++) {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> 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 tests several times, the EntrySet traverse time is much shorter than the keyset traversal time, and the performance of the EntrySet mode is usually one-fold higher than the keyset mode.
Three. Why?
by looking at source code discovery, calling Keysetmap.keyset () This method generates a Keyiterator iterator,
Its next () method returns only its key value, and then obtains its value in Keysetmap with the key value, such as: Keysetmap.get (Keysetiterator.next ())
The call to the Entrysetmap.entryset () method generates an Entryiterator iterator whose next () method returns an instance of the entry object that contains the key and value values.
If you only take its key value when traversing HashMap, then the traversal of both methods should be the same in performance.
But at the same time take the key and value value, keyset way more than EntrySet way to traverse the table, at this time keyset mode performance is poor.
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 CPU,
Using HashMap in a concurrent environment without synchronizing may cause a dead loop, which is not a bug in the Sun's official website.
HASHMAP data Structures
&NBSP;HASHMAP The main use of arrays to store data, we all know that it will hash the key, the HA operation will have a duplicate hash value, For a hash value conflict, HashMap is resolved with a linked list.
has such an attribute declaration in HashMap:
transient entry[] table;
Entry is the class that HashMap stores the data, and it has properties such as
Final K key;
V value;
Final int hash;
Entry<k,v> Next;
See 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 the entry, then all right, the new added element is also placed in the 10th position, the 10th position of the original entry assigned to the current new entry next property. It is important to note that the array stores the list of linked lists in order to resolve the hash conflict.
Several key properties
stores an array of data
transient entry[] table;
Default capacity
static final int Default_initial_ capacity = 16;
Maximum capacity
Static final int maximum_capacity = 1 <<;
The default load factor, the load factor, is a scale that hashmap capacity is expanded when the HashMap data size >= the capacity * load factor
Static final float default_load_factor = 0.75f;
When the actual data size exceeds threshold, HASHMAP will expand Capacity, threshold= capacity * load factor
int threshold;
Load factor
Final float loadfactor;
Initial procedure for
HashMap
Constructor 1:
Public HashMap (int initialcapacity, float loadfactor) { if (initialcapacity < 0) throw new IllegalArgumentException ("Illegal initial capacity:" + initialcapacity); if (initialcapacity > maximum_capacity) initialcapacity = maximum_capacity; if (loadfactor <= 0 | | Float.isnan (loadfactor)) throw new IllegalArgumentException ("Illegal load factor:" + loadfactor); Find a power of 2 >= initialcapacity int capacity = 1; while (capacity < initialcapacity) capacity <<= 1; This.loadfactor = Loadfactor; threshold = (int) (capacity * loadfactor); Table = new Entry[capacity]; Init ();
Focus on this.
while (Capacity < initialcapacity)
Capacity <<= 1;
Capacity is the initial capacity, not the initialcapacity, this should pay special attention, if the implementation of new HashMap (9,0.75);
So HashMap's initial capacity is 16, not 9, think about why.
Constructor 2
Public HashMap (Int. initialcapacity) {This (initialcapacity, default_load_factor); }
Constructor 3, all of which are default values
Public HashMap () { this.loadfactor = default_load_factor; threshold = (int) (default_initial_capacity * default_load_factor); Table = new Entry[default_initial_capacity]; Init ();
Constructor 4:
Public HashMap (map<. extends K,? extends v> m) {This (Math.max (int) (M.size ()/Default_load_factor) + 1, default_initial_capacity), default_load_factor); Putallforcreate (m); }
How to Hash
HashMap does not directly use the hashcode of an object as a hash value,
Instead, the hashcode of key is used to do some arithmetic to get the final hash value,
And the resulting hash value is not the position in the array. Oh, whether it's a get or a put or something else, the computed hash is this sentence:
int hash = hash (Key.hashcode ());
The hash function is as follows:
static int hash (int h) {
Return Usenewhash? Newhash (h): Oldhash (h);
}
Usenewhash declares as follows:
Private static Final Boolean Usenewhash;
static {Usenewhash = false;}
This shows that the Usenewhash in fact has been false and immutable, the hash function of the Usenewhash judgment is really superfluous.
private static int Oldhash (int h) { H + = ~ (h << 9); H ^= (H >>>); H + = (H << 4); H ^= (H >>>); return h; } private static int Newhash (int h) { //This function ensures, that hashcodes, differ only by //constant mult Iples at each bit position has a bounded //number of collisions (approximately 8 at default load factor). H ^= (H >>>) ^ (h >>> N); Return h ^ (H >>> 7) ^ (H >>> 4); }
The
HashMap hash function is always oldhash.
If you determine the location of the data
look at the following two lines
int hash = hash (K.hashcode ());
int i = indexfor (hash, table.length);
The first line, above, is to get the hash value,
The second line, is based on the hash refers to the calculation element in the position of the array, the calculation of the position is the hash value and array length bitwise AND operation.
static int indexfor (int h, int length) {
return H & (length-1);
What did the Put method do?
Public V put (K key, V value) { if (key = = null) return Putfornullkey (value); int hash = hash (Key.hashcode ()); int i = indexfor (hash, table.length); for (entry<k,v> e = table[i]; E! = null; e = e.next) { Object K; if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))) { V oldValue = e.value; E.value = value; E.recordaccess (this); return oldValue; } } modcount++; AddEntry (hash, key, value, I); return null; }
If key is null, it is handled separately, see the Putfornullkey method:
Private V Putfornullkey (v value) { int hash = hash (Null_key.hashcode ()); int i = indexfor (hash, table.length); for (entry<k,v> e = table[i]; E! = null; e = e.next) { if (E.key = = Null_key) { V oldValue = e.value; E.value = value; E.recordaccess (this); return oldValue; } } modcount++; AddEntry (hash, (K) Null_key, value, i); return null; }
Null_key statement: Static Final Object Null_key = new Object ();
This piece of code deals with hash collisions, which means that an object at a certain location in the array may not be unique, it is a linked list structure.
After the list is found based on the hash value, it is also traversed on the linked list, finding the object with the key equal, replacing it, and returning the old value.
for (entry<k,v> e = table[i]; E! = null; e = e.next) {
if (E.key = = Null_key) {
V oldValue = E.value;
E.value = value;
E.recordaccess (this);
return oldValue;
}
}
If the linked list is not found to have the key equal, then add the current object to the list.
modcount++;
AddEntry (hash, (K) Null_key, value, i);
return null;
And look at the AddEntry method:
void AddEntry (int hash, K key, V value, int bucketindex) { entry<k,v> e = Table[bucketindex]; Table[bucketindex] = new entry<k,v> (hash, key, value, e); if (size++ >= threshold) Resize (2 * table.length); } Table[bucketindex] = new entry<k,v> (hash, key, value, E);
Create a new entry object and put it in the head of the entry linked list at the current position, and look at the entry constructor below to see the red part.
Entry (int h, K K, v V, entry<k,v> N) {
Value = V;
Next = n;
key = k;
hash = h;
}
How to expand?
When put an element, if the capacity limit is reached, HashMap will expand, the new capacity is always twice times the original.
There is a paragraph in the Put method above:
if (size++ >= threshold)
Resize (2 * table.length);
This is the expansion of the judgment, it should be noted that the size of the data to reach the maximum capacity of HashMap only when the expansion.
Instead, the expansion is started when the value specified by threshold is reached, threshold= the maximum capacity * load factor.
Look at the Resize method:
void Resize (int newcapacity) { entry[] oldtable = table; int oldcapacity = oldtable.length; if (oldcapacity = = maximum_capacity) { threshold = Integer.max_value; return; } entry[] newtable = new entry[newcapacity]; Transfer (newtable); Table = newtable; threshold = (int) (newcapacity * loadfactor); }
Focus on the Red section of the transfer method:
void Transfer (entry[] newtable) { entry[] src = table; int newcapacity = newtable.length; for (int j = 0; J < Src.length; J + +) { entry<k,v> e = src[j]; if (E! = null) { SRC[J] = null; Do { entry<k,v> next = e.next; int i = indexfor (E.hash, newcapacity); E.next = Newtable[i]; Newtable[i] = e; e = next; } while (E! = null);}}}
The Tranfer method hashes all the elements, because the new capacity becomes larger, so the hash and position of each element are different.
Correct use of HashMap
1: Do not use HashMap in concurrent scenarios
HashMap is thread insecure, and if the operation is shared by multiple threads, it will cause unpredictable problems.
According to Sun, in the expansion of the chain will cause the closed loop, in the get element, will be infinite loop, the consequence is cpu100%.
Look at the red part of the Get method
Public V get (Object key) { if (key = = null) return Getfornullkey (); int hash = hash (Key.hashcode ()); for (entry<k,v> e = table[indexfor (hash, table.length)]; E! = null; E = e.next) { Object k; if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k)) return e.value; return null; }
2: If the data size is fixed, then it is best to set a reasonable capacity value for HashMap
Based on the above analysis, the initial default capacity of HashMap is 16, and the default load factor is 0.75.
That is, if you take the default constructor of HashMap,
When data is increased, the actual capacity of the data exceeds 10*0.75=12, the HashMap expands, The expansion brings a series of operations. Create a new array of twice times the original size, all the original elements re-hash, if your data has thousands of tens of thousands of, and with the default HashMap constructor, the result is very tragic, because HashMap constantly expanding, constantly hashing, in the use of hashmap scenes, will not be multiple threads sharing A hashmap, unless the HashMap is packaged and synchronized, the resulting memory overhead and CPU overhead may be fatal in some cases
Java Collection Framework (1) HashMap simple use and deep analysis (RPM)