Skip to content
C

HashMap

HashMap is the most commonly used implementation of the Map interface. It stores key-value pairs and does not guarantee any particular order of the entries.


1. What is HashMap?

HashMap is the most commonly used implementation of the Map interface. It stores key-value pairs and does not guarantee any particular order of the entries.

2. Why is it used?

HashMap provides very fast lookup, insertion, and deletion of key-value pairs on average, making it a go-to choice whenever quick access using a key is needed and order doesn't matter.

3. Real-Life Example

Think of a large filing cabinet where each drawer is labeled with a unique code, and you can jump directly to the right drawer using that code, without checking every drawer one by one. HashMap gives this same kind of quick, direct access using keys.

4. Syntax

java
HashMap<KeyType, ValueType> mapName = new HashMap<>();

5. Example Program

java
import java.util.HashMap; public class HashMapDemo { public static void main(String[] args) { HashMap<String, Integer> marks = new HashMap<>(); marks.put("Rahul", 85); marks.put("Sneha", 90); System.out.println(marks); } }

Output:

{Rahul=85, Sneha=90}

(Note: HashMap does not guarantee this exact order every time.)

6. Key Points to Remember

  • HashMap allows one null key and multiple null values.
  • Iteration order is not guaranteed and may vary.
  • HashMap is not synchronized, so it's not automatically thread-safe.