Recent code often appears in some cache caches to reduce the number of user requests resulting in high data server load, and these cache caches of the underlying implementation of the data structure support are map, and decided to look at the following map of the source code. So I started from HashMap. The Entry class source code in the map Entry HashMap used in 1. HashMap is as follows: In general, the Entry class is a way to implement the Map.entry interface.
Static Class Entry<k,v> implements Map.entry<k,v> {final K key; Key V value; Value entry<k,v> next; List next node pointer final int hash;
Hash value, according to the specific hash algorithm with key input for the calculation to obtain/** * Creates new entry.
*/Entry (int h, K K, v V, entry<k,v> N) {value = V;
Next = n;
key = k;
hash = h;
Public final K Getkey () {return key;
Public Final v. GetValue () {return value;
Public final V SetValue (v newvalue) {v oldValue = value;
value = newvalue;
return oldValue; Public final Boolean equals (Object o) {if (!) (
o instanceof Map.entry) return false;
Map.entry e = (map.entry) o;
Object K1 = Getkey ();
Object K2 = E.getkey (); if (k1 = = K2 | | (K1!= null && k1. Equals (K2)) {Object V1 = GetValue ();
Object v2 = E.getvalue (); if (v1 = = V2 | |
(v1!= null && v1.equals (v2)))
return true;
return false; Public final int hashcode () {return (key==null. 0:key.hashcode ()) ^ ()) ^ (value ==null?
0:value.hashcode ());
Public final String toString () {return getkey () + "=" + GetValue (); /** * This is invoked whenever the value of entry is * overwritten by a invocation
of put (K,V) for a key k that ' s already * in the HASHMAP. */void Recordaccess (hashmap<k,v> m) {}/** * This method is invoked whenever the
Entry is * removed from the table. */void Recordremoval (hashmap<k,v> m) {}}The entry class above contains a total of four data fields, I added a Chinese annotation above, you will find that the entry class is a typical single linked table node class definition (next as the next node pointer, the rest is the data field), you should already be able to think of Java HashMap Collision avoidance strategy? , is the use of external linked list collision avoidance strategy.
some basic functions in 2.HashMap 2.1 ConstructorsThe most of the parameterless constructors we use in the end are calls to the following constructors
/** * Constructs a empty <tt>HashMap</tt> with the specified initial * capacity and load factor.
* * @param initialcapacity The initial capacity initial storage capacity * @param loadfactor the load factor payload
* @throws IllegalArgumentException If the initial capacity is negative * or the load factor is nonpositive */public HashMap (int initialcapacity, float loadfactor) {if (initialcapacity < 0) th Row new IllegalArgumentException ("Illegal initial capacity:" + Initialcapa
City);
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; Guarantee HASHMThe initial storage capacity of the AP is 2 squared, and you can see this is useful in the Indexfor function while (capacity < initialcapacity) capacity <<= 1;
This.loadfactor = Loadfactor; threshold = (int) (capacity * loadfactor); HashMap the critical value for performing the resize operation is table = new entry[capacity];
Initialize Entry table, which is to initialize all buckets, each bucket is a list init (); } 2.2 from the put function
/** * Associates The specified value with the specified key into this map.
* If The map previously contained a mapping for the "key", the old * value is replaced. * * @param key key with which the specified value is associated * @param value value of * associated with The specified key * @return The previous value associated with <tt>key</tt>, or * <tt>
;null</tt> If there is no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate the map * previously associated <TT&G
T;null</tt> with <tt>key</tt>.) * * Public V put (K key, V value) {if (key = = null)//hashmap allow the key to be empty (key=null)
Fornullkey (value);
int hash = hash (Key.hashcode ()); int i = indexfor (hash, table.length); for (entry<k,v> e = table[i], e!= null; e = E.N, depending on the bucket position that determines the key-value to be inserted/updatedEXT) {//traverse corresponding bucket stored in the linked list Object K; if (E.hash = = Hash && ((k = e.key) = = Key | | key.equals (k))) {//The corresponding key value already exists, update V oldValue = E.val
Ue
E.value = value;
E.recordaccess (this); return oldValue;
Update the corresponding value}} modcount++ before returning the key; AddEntry (hash, key, value, I);
A key is not present at the bucket where the I position corresponds, then the insert operation is return null; }
2.3 Putfornullkey Add a key value pair with null keyAs you can see, key-value pairs with null key are always stored in a bucket with index 0
/**
* Offloaded version of put for null keys
/
private v Putfornullkey (v value) {for
(entry<k,v> E = Table[0]; e!= null; E = e.next) {
if (E.key = = null) {
V oldValue = e.value;
E.value = value;
E.recordaccess (this);
Return OldValue
}
}
modcount++;
AddEntry (0, NULL, value, 0); If a key-value pair with null key is not previously present, then the insert operation is eventually called return
null;
2.4 indexfor function to compute the bucket position number in the table corresponding to the key hash value
/**
* Returns index for hash code h.
*/
static int indexfor (int h, int length) {return
H & (length-1); Bit operation Hash
}
The operation of the bitwise operation is used in the function to hash the mapping, because the HASHMAP storage capability capacity is always the power of 2.
2.5 AddEntry added key-value to
/**
* Adds A new entry with the specified key, value and hash code to
* specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior.
*
/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 you look closely at the entry constructor, you will find that the
if (size++ >= threshold)
Resize (2 * table.length) is performed at the head of the chain when inserting the operation; Reconstruction of the HashMap operation, the value of each rebuild capacity is twice times the original, guaranteeing a constant of 2 of the whole number of power
}
In the English annotation, it is very clear that this function is responsible for rebuilding the map when the size of the list is the load reaches the threshold critical value, which takes a lot of time, another point to note The load calculation of HashMap is not calculated according to the proportion of the bucket position where the value exists, and its calculation is based on the number of key-value pairs we have stored capacity.
2.6 Resize Reconstruction HashMap
/** * Rehashes The contents of this map to a new array with a * larger capacity.
This are called automatically when the * number of keys in this map reaches its threshold. * * If current capacity are maximum_capacity, this method does not * Resize the map, but sets threshold to Intege
R.max_value.
* This has the effect of preventing future calls.
* * @param newcapacity The new capacity, must is a power of two; * Must be greater than current capacity unless current * capacity-maximum_capacity (in which case VA
Lue * is irrelevant).
*/void Resize (int newcapacity) {entry[] oldtable = table;
int oldcapacity = Oldtable.length; if (oldcapacity = = maximum_capacity) {threshold = Integer.max_value;
The critical value is set to the maximum, thus no new resize operation is requested.
} entry[] newtable = new Entry[newcapacity]; Transfer (newtable); Real reconstruction of HASHMAP executive function table = newtable;
threshold = (int) (newcapacity * loadfactor); }2.7 Transfer Reconstruction HashMap
/**
* Transfers all entries from the current table to newtable.
*
/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); Hash calculation
e.next = newtable[i];//Insert Newtable[i in the header of the list
= e;
e = next;
} while (e!= null);}}
You can see the reconstruction of the HashMap, not only to request new memory space, but also to hash out the existing key-value pairs.
2.2~2.7 all the procedures for the put operation.
2.8 Get Operation
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;
}
Compared with put, a get operation is a traversal lookup operation on the adjacency table structure. There are related functions such as containskey,getentry, much the same, do not say more.
2.9 Remove
/** * Removes the mapping for the specified key from this map if present. * * @param key key whose mapping is to removed the map * @return the previous value associated
; tt>key</tt>, or * <tt>null</tt> if there is no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate the map * previously associated
;tt>null</tt> with <tt>key</tt>.)
*/Public V Remove (Object key) {entry<k,v> E = Removeentryforkey (key);
return (E = null null:e.value); }/** * Removes and returns the entry associated with the specified key * in the HASHMAP.
Returns NULL if the HASHMAP contains no mapping * for this key.
* * Final entry<k,v> Removeentryforkey (Object key) {int hash = (key = = null)? 0:hash (Key.hashcode ());
int i = indexfor (hash, table.length); Entry<k,v> prev = table[i];
entry<k,v> e = prev;
while (e!= null) {entry<k,v> next = E.next;
Object K; if (E.hash = = Hash && (k = e.key) = = Key | | (Key!= null && key.equals (k)))
{modcount++;
size--;
if (prev = = e) Table[i] = next;
else Prev.next = next;
E.recordremoval (this);
return e;
} prev = e;
e = next;
return e; }Delete operation is the deletion of the single linked list ~ ~
3. Concurrent support and related summary(ˇˍˇ) To continue to write down when found this article is too good to write, so give the following link: http://coolshell.cn/articles/9606.html
Sincerely give the author of this article a compliment. HashMap support concurrent access, the use of hashmap in multiple threads can cause a dead loop condition. Then there's concurrenthashmap~~.