Blog

Java HashMap

Key Takeaways

  • A HashMap stores data as key/value pairs for quick lookup.
  • Use HashMap for unordered data with fast access needs.
  • HashMap is not synchronized, unlike Hashtable.
  • Useful when ordering is unnecessary, prefer LinkedHashMap for ordered data.

What is a HashMap?

A HashMap is a data structure in Java that stores data in the form of key/value pairs, providing fast retrieval time:

HashMap<String, Integer> people = new HashMap<>();
people.put("Sam", 45);
people.put("Brenda", 32);
int age = people.get("Sam"); //returns 45

This example demonstrates creating a HashMap where each entry is a pair with a string key and an integer value. You use put() to add and get() to retrieve data.

When should you use a HashMap?

Use a HashMap when you need to store and look up data efficiently with keys. This structure is ideal when you don't care about the order of entries. A HashMap allows for near constant time complexity (O(1)) for inserting and retrieving data.

If maintaining the order of entries is important, consider using a LinkedHashMap, which combines the key mapping capabilities of a HashMap with the predictable iteration order.

For thread-safe needs, remember HashMap is not synchronized. If concurrency is a concern, you can explore ConcurrentHashMap instead, which provides a thread-safe solution.

Java HashMap Implementation

Beneath the surface, a HashMap utilizes an array-based structure. It calculates the index for keys using a hashing function, making access times efficient. Collisions—where different keys are hashed to the same index—are managed through linked lists or, in newer Java versions, balanced trees.

Understanding this under-the-hood mechanism helps you optimize performance by choosing appropriate initial capacities and load factors, reducing the need for resizing.

Java HashMap Examples

Here's a simple example of a HashMap:

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 100);
scores.put("Bob", 85);
int aliceScore = scores.get("Alice"); //returns 100

This sets up a scoring system where names are stored as string keys with integer values representing scores. For more in-depth examples and nuanced uses, explore our dedicated Java HashMap examples.

Java HashMap vs Hashtable

Both HashMap and Hashtable store data as key/value pairs but differ primarily in synchronization. Hashtable is synchronized, making it thread-safe but slower. In scenarios where multiple threads access a Map concurrently without external synchronization, consider using ConcurrentHashMap instead, as it offers better concurrency support.

For more details on distinctions, visit Java HashMap vs Hashtable.

FAQ

Can HashMap store null keys and values?

Yes, a HashMap can store one null key and multiple null values.

What happens when different keys have the same hashcode?

HashMap resolves collisions using linked lists (or trees in recent Java versions) for keys that hash to the same bucket.

How to synchronize a HashMap?

You can synchronize a HashMap externally by wrapping it with Collections.synchronizedMap(new HashMap<>()) or use ConcurrentHashMap for more granular synchronization.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews