What are the features of Java Hashmap?

Features of Java HashMap

1. Key-Value Pair Storage:

   Explanation: HashMap stores data in key-value pairs where each key is unique. It allows efficient retrieval, insertion, and deletion of elements based on keys.

2. Hashing Mechanism

   Explanation: Internally, HashMap uses a hashing technique 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. Null Keys and Values:

   – Explanation: HashMap allows null values and exactly one null key. This flexibility can be useful when handling data where null values or keys might be valid or expected.

4. Performance:

    Explanation: HashMap provides constant-time performance (O(1)) for basic operations (get and put) under ideal circumstances, making it suitable for scenarios where fast lookups are required.

5. Iterating Over Entries

   Explanation: HashMap supports iterating over its entries using iterators or the enhanced for-loop, allowing easy traversal and manipulation of key-value pairs.

6. Concurrency:

   Explanation: HashMap is not synchronized, meaning it is not thread-safe. Concurrent modifications can lead to ConcurrentModificationException. For thread-safe operations, consider using ConcurrentHashMap or synchronizing HashMap externally.

Java Hashmap

Example in Java

Let’s demonstrate the features of HashMap with a Java example:

Example
java
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
        System.out.println("All student scores:");
        for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // Adding a null key and value
        studentScores.put(null, 100);
        System.out.println("Score for null key: " + studentScores.get(null));

        // Size of HashMap
        System.out.println("Number of students: " + studentScores.size());
    }
}

Explanation: Java Hashmap

  • HashMap stores key-value pairs (“Alice” -> 95, “Bob” -> 85, “Carol” -> 90, null -> 100) internally based on their hash codes.
  • get() method retrieves values based on the hashed index of the key (studentScores.get(“Alice”)).
  • entrySet() allows iteration over key-value pairs (for (Map.Entry entry : studentScores.entrySet())).
  • put(null, 100) adds a null key and value (studentScores.put(null, 100)).
  • size() method returns the number of key-value pairs currently stored in the HashMap.

Homepage

Readmore