We will find out answers for the following question
- What is HashMap in Java
- Common methods available
- HashMap is a Map-based collection class that is used to store Key & value pairs.
- It is denoted as HashMap<Key, Value> or HashMap<K, V>.
- This class makes no guarantees as to the order of the map.
- It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).
The above code simply shows how to add and retrieve values from a HashMap.
Based on the output, Even though we tried adding multiple null keys but only one null key is allowed.
This is not the case with value. As multiple null values are allowed in Hashmap.
hmap.clear(); => The map will be empty after this call returns. Returns void. hmap.containsKey(12); => Returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)) hmap.containsValue("Hello"); => Returns true if this map maps one or more keys to the specified value hmap.getOrDefault(12, "No Value"); => Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key hmap.size(); => Returns int the number of key-value mappings in this map . If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE. hmap.isEmpty(); => Returns true if this map contains no key-value mappings hmap.replace(12, "test"); => Replaces the entry for the specified key only if it is currently mapped to some value. hmap.put(1, "Hello"); => Returns the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports
- HashMap is unsynchronized, so its not thread-safe and is not advisable to use in a multi-threading Environment.
- HashMap permits one null key and multiple null values.
- Pay extra attention to the methods provided by HashMap. There input and return type.
How null key is handled in HashMap?
- Since equals() and hashCode() are used to store and retrieve values, how does it work in case of null key?
- The null key is handled specially in HashMap, there are two separate methods for that putForNullKey(V value) and getForNullKey()
- Null keys always map to index 0.
- Here is how nulls are retrieved from HashMap
Internal Structure of Hashmap
Internally HashMap contains an array of Node. Node is represented as a class which contains 4 fields :
- int hash
- K key
- V value
- Node next
HashMap in Java works on Hashing Technique.