What is HashMap?
HashMap is work on the hashing principle. HashMap is a data structure which allows us to store object and retrieve an object in constant time O(1) via a key. Key is an important factor that we use to get and put data in a data structure like HashMap, ConcurrentHashMap, etc.
HashMap backed by an array(is also called Bucket) which further uses LinkedList (means, every array index turns itself into LinkedList).
On whole, every key and value in combination in HashMap is an object. This object is also called (Map.Entry) object. HashMap has a static Entry class for creating (Map.Entry) objects.
Entry<K, V> class ⇒ It’s a static inner class in HashMap which implements further implements Map inner interface by the name Entry (interface Entry<K, V> {}).
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
}
As per the above code, every (Map.Entry) object has four variables i.e.: the key which is constant via final, the value of V type, next node as per LinkedList architecture and hash which is final int value.
Here, we have a Hash function which is used to link key and value in HashMap. Objects are stored by calling put (key, value) method of HashMap and retrieved value by calling get(key) method.
What happens when we call the put method? ⇒ put() API
When we call the put method <variable-name>.put(key, value). On key, we called the hashCode method.
Before going further, Must know What is hashCode.
HashCode is a unique value to every object but sometimes it returns the same value for different objects. HashCode is a native method of Object class. It’s doesn’t represent any address related java objects. JDK designers further using this, to calculate the hash value.
JDK designers well assumed that there might be some poorly written
hashCode() functions that can return very high or low hash code value.
After calling hashCode on the key object. We call the hash static function of the HashMap class.
Here, the static Hash function returns a value that is further used to find Bucket location (array index) with the help of indexFor method. It’s necessary because we need an index under the size of the table array of Entry type. By default size of HashMap is 16, if we don’t provide.
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
Here, the table is a type ⇒ transient Entry[] table; in HashMap to Entry class objects and i represents array index which is also called bucket location.
If Array (Bucket) Index Location is Empty?
We get the location i.e.: index in the array. Suppose to be index is 3 and this bucket location is empty as well. We put the Entry object in 3 indexes of the table. There is only one element as of now so the next Node is Null by default.