Java, Kotlin: HashMap Under the hood?

Leo N
Level Up Coding
Published in
5 min readOct 19, 2020

--

Definition

Java HashMap class is an implementation of Map interface based on hash table. It stores elements in key & value pairs which is denoted as HashMap<Key, Value> or HashMap<K, V>.

It extends AbstractMap class, and implements Map interface and can be accessed by importing java.util package. Declaration of this class is given below.

Java (java.util)

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

Kotlin (kotlin.collections)

expect class HashMap<K, V> : MutableMap<K, V>

Create a HashMap:

// HashMap creation with 8 capacity and 0.6 load factor
HashMap<Key, Value> numbers = new HashMap<>(8, 0.6f);

Notice the part new HashMap<>(8, 0.6). Here, the first parameter is capacity and the second parameter is loadFactor.

  • load factor : The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. 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 (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
  • capacity : The capacity is the number of buckets in the hash table( HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.), and the initial capacity is simply the capacity at the time the hash table is created

How it works?

HashMap in Java works on hashing principles. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method. When we call put method, the hashcode() method of the key object is called so that the hash…

--

--

Leo N
Level Up Coding

🎓 “A person who never made a mistake never tried anything new.” — Albert Einstein