Public synchronized V put (K key, V value ){
// Make sure the value is not null
If (value = null ){
Throw new NullPointerException ();
}
// Makes sure the key is not already in the hashtable.
Entry tab [] = table;
Int hash = key. hashCode ();
Int index = (hash & 0x7FFFFFFF) % tab. length;
For (Entry <K, V> e = tab [index]; e! = Null; e = e. next ){
If (e. hash = hash) & e. key. equals (key )){
V ld = e. value;
E. value = value;
Return old;
}
}
ModCount ++;
If (count> = threshold ){
// Rehash the table if the threshold is exceeded
Rehash ();
Tab = table;
Index = (hash & 0x7FFFFFFF) % tab. length;
}
// Creates the new entry.
Entry <K, V> e = tab [index];
Tab [index] = new Entry <K, V> (hash, key, value, e );
Count ++;
Return null;
}
This takes a long look. You only need to pay attention to three points,
1. index. index is the hashcode of the key value and the & Operation of 0x7fffff. Then, the remainder value is obtained based on the array length. In this way, you can determine the name of the queue,
2,
For (Entry <K, V> e = tab [index]; e! = Null; e = e. next ){
If (e. hash = hash) & e. key. equals (key )){
V ld = e. value;
E. value = value;
Return old;
}
}
In the for statement, e is used to traverse a queue named index single linked list in the tab. The definitions of the first single linked list are defined by index to see if the queue already has the same value. If yes, returns this value.
3. If not, add
Entry <K, V> e = tab [index];
Tab [index] = new Entry <K, V> (hash, key, value, e );
3. get (Object)
Public synchronized V get (Object key ){
Entry tab [] = table;
Int hash = key. hashCode ();
Int index = (hash & 0x7FFFFFFF) % tab. length;
For (Entry <K, V> e = tab [index]; e! = Null; e = e. next ){
If (e. hash = hash) & e. key. equals (key )){
Return e. value;
}
}
Return null;
}
This is a good understanding of int index = (hash & 0x7FFFFFFF) % tab. length;
Get queue name,
For (Entry <K, V> e = tab [index]; e! = Null; e = e. next ){
If (e. hash = hash) & e. key. equals (key )){
Return e. value;
}
}
Traverse the team and obtain the specific value based on the hash value.
In summary, one is to determine the queue based on the index and obtain the specific element value from the hash value.
After reading hashtable, let's take a look at hashMap.
HashMap can be regarded as an upgraded version of hashtable, which was first available since 1.2.
However, there are two main differences between the two.
1. The read and write operations of hashMap are unsynchronized. Be sure to use it in a multi-threaded environment.
Hashtable is synchronized.
The difference between the two is achieved by adding the synchronized keyword to the read/write method.
The second difference is that hashMap can empty values, and hashtable will report an error.