Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java WeakHashMap – Understanding, Usage, and Key Differences

Java WeakHashMap

A comprehensive guide to Java’s WeakHashMap, covering its creation, key differences from HashMap, practical examples, and essential methods.

The WeakHashMap class is part of the Java Collections Framework and implements the Map interface. It behaves like a normal hash table but stores keys as weak references, allowing them to be reclaimed by the garbage collector when no longer in use.

Java WeakHashMap – Understanding, Usage, and Key Differences

Note: Keys in a WeakHashMap are wrapped in WeakReference objects.

A weak reference can be garbage‑collected if the program no longer holds a strong reference to the key object.


Creating a WeakHashMap

First, import java.util.WeakHashMap:

import java.util.WeakHashMap;

Then instantiate it, optionally specifying an initial capacity and load factor:

// WeakHashMap with a capacity of 8 and a load factor of 0.6
WeakHashMap<Key, Value> numbers = new WeakHashMap<>(8, 0.6);

Parameters:

When no parameters are supplied, the default values apply:

WeakHashMap<Key, Value> numbers = new WeakHashMap<>();

HashMap vs. WeakHashMap

While both implement Map, the key distinction lies in reference strength:

Example demonstrating the behavior:

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();
        String two = new String("Two");
        Integer twoValue = 2;
        String four = new String("Four");
        Integer fourValue = 4;

        numbers.put(two, twoValue);
        numbers.put(four, fourValue);
        System.out.println("WeakHashMap: " + numbers);

        // Nullify the reference to the key
        two = null;
        System.gc();
        System.out.println("WeakHashMap after GC: " + numbers);
    }
}

Output:

WeakHashMap: {Four=4, Two=2}
WeakHashMap after GC: {Four=4}

The entry for “Two” disappears because its key is no longer strongly reachable. In contrast, a HashMap would retain the entry:

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> numbers = new HashMap<>();
        String two = new String("Two");
        Integer twoValue = 2;
        String four = new String("Four");
        Integer fourValue = 4;

        numbers.put(two, twoValue);
        numbers.put(four, fourValue);
        System.out.println("HashMap: " + numbers);

        two = null;
        System.gc();
        System.out.println("HashMap after GC: " + numbers);
    }
}

Output:

HashMap: {Four=4, Two=2}
HashMap after GC: {Four=4, Two=2}

Thus, WeakHashMap is ideal when you want the map to automatically release memory tied to unused keys.


Converting from Another Map

Instantiate a WeakHashMap from an existing map to copy its entries:

import java.util.HashMap;
import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> evenNumbers = new HashMap<>();
        String two = new String("Two");
        evenNumbers.put(two, 2);
        System.out.println("HashMap: " + evenNumbers);

        WeakHashMap<String, Integer> numbers = new WeakHashMap<>(evenNumbers);
        System.out.println("WeakHashMap: " + numbers);
    }
}

Output:

HashMap: {Two=2}
WeakHashMap: {Two=2}

Key Methods of WeakHashMap

Below is a selection of the most frequently used operations.

Inserting Entries

Example:

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        WeakHashMap<String, Integer> evenNumbers = new WeakHashMap<>();
        evenNumbers.put(new String("Two"), 2);
        evenNumbers.putIfAbsent(new String("Four"), 4);
        System.out.println("Even numbers: " + evenNumbers);

        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();
        numbers.put(new String("One"), 1);
        numbers.putAll(evenNumbers);
        System.out.println("All numbers: " + numbers);
    }
}

Output:

Even numbers: {Four=4, Two=2}
All numbers: {Two=2, Four=4, One=1}

Accessing Entries

Retrieve data via:

Example:

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();
        numbers.put(new String("One"), 1);
        numbers.put(new String("Two"), 2);
        System.out.println("Map: " + numbers);
        System.out.println("Entry set: " + numbers.entrySet());
        System.out.println("Keys: " + numbers.keySet());
        System.out.println("Values: " + numbers.values());
        System.out.println("Get Two: " + numbers.get("Two"));
        System.out.println("GetOrDefault Four: " + numbers.getOrDefault("Four", 4));
    }
}

Output:

Map: {Two=2, One=1}
Entry set: [Two=2, One=1]
Keys: [Two, One]
Values: [1, 2]
Get Two: 2
GetOrDefault Four: 4

Removing Entries

Example:

import java.util.WeakHashMap;

class Main {
    public static void main(String[] args) {
        WeakHashMap<String, Integer> numbers = new WeakHashMap<>();
        numbers.put(new String("One"), 1);
        numbers.put(new String("Two"), 2);
        System.out.println("Map: " + numbers);

        int removed = numbers.remove("Two");
        System.out.println("Removed value: " + removed);

        boolean removedIf = numbers.remove("One", 3);
        System.out.println("Removed {One=3}? " + removedIf);

        System.out.println("After removal: " + numbers);
    }
}

Output:

Map: {Two=2, One=1}
Removed value: 2
Removed {One=3}? false
After removal: {One=1}

Additional Utilities

MethodDescription
clear()Deletes all entries.
containsKey(key)Checks if the key exists.
containsValue(value)Checks if a value is present.
size()Returns the number of entries.
isEmpty()Returns true if the map has no entries.

For a deeper dive, refer to the official Java WeakHashMap documentation.


Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Java Comments: Types, Usage, and Best Practices
  3. Mastering Java if…else: Control Flow Explained
  4. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  5. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  6. Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
  7. Java Annotations Explained: Types, Placement, and Practical Examples
  8. Mastering Java HashMap: Operations, Examples, and Best Practices
  9. Java WeakHashMap – Understanding, Usage, and Key Differences
  10. Java HashMap: A Comprehensive Guide