HashMap in Java

Naveen AnamaneniUpdated · 5 min read

HashMap in Java is a class that implements the Map interface using a hash table. It is used to store key-value pairs and to find a value by its key very quickly, in constant time on average. HashMap allows one null key and any number of null values, and it does not keep any order. It is the most widely used map in Java. In this lesson, you will learn how to create a HashMap, use its methods, and make your own classes work as keys.

Declaration

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

Features of HashMap

  • Unique keys, any values.
  • No order: iteration order depends on hash codes and can change as the map grows.
  • One null key and many null values.
  • Fast: put, get, remove and containsKey are O(1) on average.
  • Default capacity 16, load factor 0.75: it resizes when it becomes three-quarters full.
  • Not synchronized.

Constructors

ConstructorDescription
HashMap()It creates an empty map with capacity 16 and load factor 0.75.
HashMap(int initialCapacity)It creates an empty map with the given capacity.
HashMap(int initialCapacity, float loadFactor)It creates an empty map with the given capacity and load factor.
HashMap(Map<? extends K, ? extends V> m)It creates a map with the same pairs as another map.

Example: A Simple Phone Book

Let's see an example of the common operations.

PhoneBook.java▶ Try it
import java.util.HashMap;
import java.util.Map;
 
public class PhoneBook {
    public static void main(String[] args) {
        Map<String, String> phones = new HashMap<>();
        phones.put("Navika", "98480-11111");
        phones.put("Srihitha", "98480-22222");
        phones.put("Advitha", "98480-33333");
 
        System.out.println("Navika: " + phones.get("Navika"));
        System.out.println("Count: " + phones.size());
 
        phones.put("Navika", "90000-44444");
        System.out.println("Navika now: " + phones.get("Navika"));
 
        System.out.println("Unknown: "
            + phones.getOrDefault("Anamaneni", "not saved"));
        phones.remove("Advitha");
        System.out.println("Has Advitha? " + phones.containsKey("Advitha"));
    }
}
Output
Navika: 98480-11111
Count: 3
Navika now: 90000-44444
Unknown: not saved
Has Advitha? false

Explanation: put stores each name and number. Putting Navika again replaces the old number instead of adding a second entry, so the count stays 3. getOrDefault returns a fallback when the key is missing, and remove deletes a pair.

The Order Isn't Guaranteed

NoOrder.java▶ Try it
import java.util.HashMap;
import java.util.Map;
 
public class NoOrder {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<>();
        m.put("Navika", 1);
        m.put("Srihitha", 2);
        m.put("Advitha", 3);
        m.put("Anamaneni", 4);
        System.out.println(m);
    }
}
Output
{Anamaneni=4, Navika=1, Srihitha=2, Advitha=3}

Explanation: The pairs come out in the order of their buckets, which depends on each key's hash code, not on when they were added. This order may differ between Java versions or after the map resizes, so code must never depend on it. "HashMap Internal Working" shows exactly how the bucket is chosen.

Using Your Own Class as a Key

A key class must override equals and hashCode, and should be immutable. A record does both automatically:

RecordKey.java▶ Try it
import java.util.HashMap;
import java.util.Map;
 
public class RecordKey {
    record Seat(int row, int number) { }
 
    public static void main(String[] args) {
        Map<Seat, String> booking = new HashMap<>();
        booking.put(new Seat(5, 12), "Navika");
        booking.put(new Seat(5, 13), "Srihitha");
 
        System.out.println(booking.get(new Seat(5, 12)));
        System.out.println(booking.containsKey(new Seat(9, 1)));
    }
}
Output
Navika
false

Explanation: new Seat(5, 12) used in get is a different object from the one used in put, but records compare by their data, so the map finds Navika's booking.

Common Mistakes

Using a mutable object as a key and then changing it. The entry becomes unreachable.

Overriding equals but not hashCode in a key class. Lookups with an equal object fail.

Sharing a HashMap between threads without synchronization. Use ConcurrentHashMap.

Interview Corner

What is a HashMap in Java?

HashMap<K, V> is a hash-table-based implementation of Map that stores key-value pairs with unique keys. It offers average O(1) put, get and remove, allows one null key and multiple null values, doesn't guarantee any iteration order, and isn't synchronized. It starts with 16 buckets and a load factor of 0.75, and doubles its bucket array when the number of entries exceeds capacity times load factor.

Practice

  1. Easy: Store the prices of five fruits in a HashMap and print the price of a fruit the user asks for, or "not sold" if it's missing.
  2. Harder: Create a Point(int x, int y) record and use it as a key in a map from points to place names. Check that a new Point with the same coordinates finds the place.

Quick check: HashMap

4 questions
1How many null keys can a HashMap have?
2What is the default capacity of a HashMap?
3Does a HashMap keep insertion order?
4What must a custom key class override?

Key Takeaways

Was this tutorial helpful?

Lesson 282 of 482