HashMap 運作原理 (from Internal Working of HashMap in Java )
Internal Structure of HashMap
HashMap conatins an array of Node.
Node class containis:
- int hash
- K key
- V value
- Node next
Buckets
- A bucket is one element of HashMap array. It is used to store nodes.
- A single bucket can have more than one nodes, it depends on hashCode() method.
- Default initial capacity(number of bucket) =
16
, load factor =0.75f
(75%) - When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed so that the hash table has approximately twice the number of buckets.
after storing the 12th(16 * 0.75) data into the HashMap, its capacity becomes 32(16*2).
Index Calculation in HashMap
index = hashCode(key) % n
n: number of buckets or size of array
91 % 16 = 11, 155 % 16 = 11, 171 % 16 = 11
from: Java之美[從菜鳥到高手演變]之HashMap、HashTable
Put Data
Initially Empty hashMap
HashMap map = new HashMap();
Inserting Key-Value Pair
map.put(new Key("vishal"), 20);
Steps:
- Hash code of Key{"vishal"} is
118
. - Index is
6
. Create a node object as :
{ int hash = 118 // {"vishal"} is not a string but // an object of class Key Key key = {"vishal"} Integer value = 20 Node next = null }
Place this object at index 6, if no other object is presented there.
- Hash code of Key{"vishal"} is
Inserting another Key-Value Pair
map.put(new Key("sachin"),30);
In Case of collision
map.put(new Key("vaibhav"),40);
Steps:
- Hash code of Key {“vaibhav”} is
118
. - Index is
6
. Create a node object a:
{ int hash = 118 Key key = {"vaibhava"} Integer value = 40 Node next = null }
In this case a node object is found at the index 6 – this is a case of collision.
Check if both the keys are same via equals().
- if key are same, replace the value with current value.
- Otherwise connect this node object to the previous node object via linked list.
- Hash code of Key {“vaibhav”} is
Get Data
Fetch the data for key vaibahv
map.put(new Key("vaibhav"),40);
Steps:
- Hash code of Key {“vaibhav”} is
118
. - Index is
6
. - Go to index 6 of array and compare first element’s key with given key. If both are equals then return the value,
otherwise check for next element if it exists.
- Hash code of Key {“vaibhav”} is
Java Code
import java.util.HashMap;
class Key
{
String key;
Key(String key)
{
this.key = key;
}
@Override
public int hashCode()
{
int hash = (int)key.charAt(0);
System.out.println("hashCode for key: "
+ key +" = "+ hash);
return hash;
}
@Override
public boolean equals(Object obj)
{
return key.equals(((Key)obj).key);
}
}
// Driver class
public class GFG
{
public static void main(String[] args)
{
HashMap map = new HashMap();
map.put(new Key("vishal"), 20);
map.put(new Key("sachin"), 30);
map.put(new Key("vaibhav"), 40);
System.out.println();
System.out.println("Value for key sachin: " +
map.get(new Key("sachin")));
System.out.println("Value for key vaibhav: " +
map.get(new Key("vaibhav")));
}
}