Guide to Java HashMap

本文最后更新于:2022年9月13日 下午

HashMap in Java is a collection class that implements the Map interface. It is used to store key & value pairs. Each key is mapped to a single value in the map.

Keys are unique. It means we can insert a key ‘K’ only once in a map. Duplicate keys are not allowed. Though a value 'V' can be mapped to multiple keys.

1. java.util.HashMap Class

1.1. HashMap class declaration

HashMap has been declared as follows:

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

1.2. HashMap class Hierarchy

As shown above, HashMap implements Map interface and extends AbstractMap class.

2. Java HashMap Features

  • HashMap cannot contain duplicate keys.
  • HashMap allows multiple null values but only one null key.
  • HashMap is an unordered collection. It does not guarantee any specific order of the elements.
  • HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap. Or you can use Collections.synchronizedMap(hashMap) to get the synchronized version of HashMap.
  • A value can be retrieved only using the associated key.
  • HashMap stores only object references. So primitives must be used with their corresponding wrapper classes. Such as int
  • will be stored as Integer.
  • HashMap implements Cloneable and Serializable interfaces.

3. Internal Implementation of HashMap

HashMap works on principle of hashing. Hashing is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. Each object in java has it’s hash code in such a way that two equal objects must produce the same hash code consistently.

3.1. HashMap.Entry class

The key-value pairs are stored as instances of the inner class HashMap.Entry which has key and value mapping stored as attributes. key has been marked as final.

static class Entry<K ,V> implements Map.Entry<K, V>
{
    final K key;
    V value;

    Entry<K ,V> next;
    final int hash;

    ...//More code goes here
}

3.2. Internal working

All instances of Entry class are stored in an array declared as 'transient Entry[] table'. For each key-value to be stored in HashMap, a hash value is calculated using the key’s hash code. This hash value is used to calculate the index in the array for storing Entry object.

In case of collision, where multiple keys are mapped to a single index location, a linked list is formed to store all such key-value pairs that should go in a single array index location.

While retrieving the value by key, the first index location is found using key’s hashcode. Then all elements are iterated in the LinkedList, and the correct value object is found by identifying the correct key using its equals() method.

4. Java HashMap Example

Let’s quickly go through some examples to work with HashMap in Java.

4.1. Add key-value – HashMap.put()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.HashMap;

public class HashMapExample
{
public static void main(String[] args) throws CloneNotSupportedException
{
HashMap<Integer, String> map = new HashMap<>();

map.put(1, "A");
map.put(2, "B");
map.put(3, "C");

System.out.println(map);
}
}

Program output.

1
{1=A, 2=B, 3=C}

4.2. Get value by key – HashMap.get()

1
2
3
4
5
6
7
8
9
HashMap<Integer, String> map = new HashMap<>();

map.put(1, "A");
map.put(2, "B");
map.put(3, "C");

String value = map.get(2);

System.out.println("The value is :: "+ value );

Program output.

1
The value is :: B

4.3. Remove pair by key – HashMap.remove()

1
2
3
4
5
6
7
8
9
10
11
HashMap<Integer, String> map = new HashMap<>();

map.put(1, "A");
map.put(2, "B");
map.put(3, "C");

System.out.println(map);

map.remove(3);

System.out.println(map);

Program output.

1
2
{1=A, 2=B, 3=C}
{1=A, 2=B}

4.4. Iterate a HashMap

Please note that iterators of this class are fail-fast and if any structure modification is done after creation of iterator, it will throw ConcurrentModificationException.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
HashMap<Integer, String> map = new HashMap<>();

map.put(1, "A");
map.put(2, "B");
map.put(3, "C");

System.out.println("//Iterate over keys");

Iterator<Integer> itr = map.keySet().iterator();

while (itr.hasNext())
{
Integer key = itr.next();
String value = map.get(key);

System.out.println("The key is :: " + key + ", and value is :: " + value );
}

System.out.println("//Iterate over entries set");

Iterator<Entry<Integer, String>> entryIterator = map.entrySet().iterator();

while (entryIterator.hasNext())
{
Entry<Integer, String> entry = entryIterator.next();

System.out.println("The key is :: " + entry.getKey() + ", and value is :: " + entry.getValue() );
}

Program output.

1
2
3
4
5
6
7
8
9
//Iterate over keys
The key is :: 1, and value is :: A
The key is :: 2, and value is :: B
The key is :: 3, and value is :: C

//Iterate over entries set
The key is :: 1, and value is :: A
The key is :: 2, and value is :: B
The key is :: 3, and value is :: C

5. HashMap Methods

List of methods in HashMap class and their short description.

  1. void clear() : removes all the key-value pairs from the HashMap.
  2. Object clone() : returns a shallow copy of the specified HashMap.
  3. boolean containsKey(Object key) : returns true or false based on whether the specified key is found in the map or not.
  4. boolean containsValue(Object Value) : Similar to containsKey() method, it looks for the specified value instead of key.
  5. Object get(Object key) : returns the value for the specified key in the HashMap.
  6. boolean isEmpty() : checks whether the map is empty.
  7. Set keySet() : returns the Set of all keys stored in the HashMap.
  8. Object put(Key k, Value v) : Inserts key-value pair into the HashMap.
  9. int size() : returns the map size equal to the number of key-value pairs stored in the HashMap.
  10. Collection values() : returns a collection of all values in the map.
  11. Value remove(Object key) : removes the key-value pair for the specified key.
  12. void putAll(Map m) : copies all the elements of a map to another specified map.

6. HashMap Examples

7. References


Guide to Java HashMap
https://baymax55.github.io/2022/09/13/java/Guide-to-Java-HashMap/
作者
baymax55
发布于
2022年9月13日
许可协议