Explain a HashMap
In Java, HashMap is a part of the Java Collections Framework and implements the Map interface. It provides a way to store key-value pairs where each unique key maps to a single value. Here’s an explanation followed by a Java example:
Table of Contents
Explanation of Hash Map
1. Key-Value Storage
Explanation: Hash Map stores data in key-value pairs, where each key is unique. This allows efficient retrieval, insertion, and deletion of elements based on keys.
2. Hashing Mechanism
Explanation: Internally, Hash Map uses a hashing mechanism to store and retrieve elements. Keys are hashed, and the hash code determines the bucket location where the key-value pair will be stored.
3. Performance
Explanation: Hash Map provides constant-time performance for basic operations (get and put) under ideal circumstances, making it suitable for scenarios where fast lookups are required.
Example in Java
Let’s demonstrate the use of Hash Map with a simple Java example:
import java.util.*;
public class Main {
public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> studentScores = new HashMap<>();
// Adding key-value pairs
studentScores.put("Alice", 95);
studentScores.put("Bob", 85);
studentScores.put("Carol", 90);
// Accessing elements
System.out.println("Alice's score: " + studentScores.get("Alice"));
// Iterating over HashMap
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + "'s score: " + entry.getValue());
}
// Removing a key
studentScores.remove("Bob");
// Checking existence of a key
if (studentScores.containsKey("Bob")) {
System.out.println("Bob's score: " + studentScores.get("Bob"));
} else {
System.out.println("Bob's score not found.");
}
// Size of HashMap
System.out.println("Number of students: " + studentScores.size());
}
}
Explanation: In this example:
- Map studentScores declares a Hash Map where keys are String (student names) and values are Integer (scores).
- put() method adds key-value pairs (studentScores.put(“Alice”, 95)).
- get() method retrieves values based on keys (studentScores.get(“Alice”)).
- entrySet() allows iteration over key-value pairs.
- remove() removes a key-value pair (studentScores.remove(“Bob”)).
- containsKey() checks if a key exists (studentScores.containsKey(“Bob”)).
- size() returns the number of key-value pairs in the Hash Map.