Java HashMap Class

Category: Java   Tags: Java, Java Collection, Java Map Interface, Java HashMap Class

HashMap class extends AbstractMap and implements the Map interface. HashMap has this declaration:

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

Here, K specifies the type of keys, and V specifies the type of values. This class makes no guarantees that the order will remain constant over time. HashMap permits null values and the null key. It is a unsynchronized class. Get and put operations provides constant-time performance.

The two parameters that affect HashMap performance: initial capacity and load factor. According to Java Documentation:

The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. 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.

Constructors

HashMap()
It will create an empty HashMap with an initial capacity of 16 and default load factor (0.75).
HashMap(int capacity)
It will create an empty HashMap with an initial capacity specified by capacity and default load factor (0.75).
HashMap(int capacity, float loadFactor)
It will create an empty HashMap with an initial capacity specified by capacity and load factor loadFactor.
HashMap(Map<? extends K, ? extends V> map)
It creates a HashMap containing the elements of the specified map map.

HashMap is not synchronized. Therefore if multiple thread is accessing the map then it must synchronized externally. You can check out this post about synchronization. You can use Collections.synchronizedMap also to synchronize the hash map:

                                    Map m = Collections.synchronizedMap(new HashMap());
                                

The returned iterator of this class are fail-fast i.e during iterating the hashmap if you do any modification, it will throw ConcurrentModificationException exception. Here is one HashMap example:

JavaHashMapDemo.java

                            package com.tutorial.java.collections;

                            import java.util.HashMap;
                            import java.util.Iterator;
                            import java.util.Map;
                            import java.util.Set;

                            public class JavaHashMapDemo {

                                public static void main(String[] args) {
                                    HashMap<Integer, String> map = new HashMap<>();
                                    map.put(10, "Value of 10");
                                    map.put(11, "Value of 11");
                                    map.put(12, "Value of 12");

                                    System.out.println("Size: " + map.size());
                                    System.out.println("Has key 10?: " + map.containsKey(10));
                                    System.out.println("Has key 100?: " + map.containsKey(100));
                                    System.out.println("Value of key 10: " + map.get(10));
                                    System.out.println("Showing all elements:");
                                    Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
                                    Iterator<Map.Entry<Integer, String>> iterator = entrySet.iterator();

                                    while (iterator.hasNext()) {
                                        Map.Entry<Integer, String> entry = iterator.next();
                                        System.out.println(entry.getKey() + " --> " + entry.getValue());
                                    }
                                }

                            }
                        

Output:

                            Size: 3
                            Has key 10?: true
                            Has key 100?: false
                            Value of key 10: Value of 10
                            Showing all elements:
                            10 --> Value of 10
                            11 --> Value of 11
                            12 --> Value of 12
                          

The Map.Entry Interface

The Map.Entry interface enables you to work with a map entry. Map.Entry is generic and is declared like this:

                                    interface Map.Entry<K,V>
                                

Here, K specifies the type of keys, and V specifies the type of values. The getKey() method returns the key for this map entry and getValue() method returns the value for this map entry.