Java WeakHashMap Class: A Beginner's Guide

Introduction

Hello there, future Java programmers! Today, we're going to dive into the fascinating world of WeakHashMap in Java. Don't worry if you've never heard of it before – we'll start from the very beginning and work our way up. By the end of this tutorial, you'll be a WeakHashMap expert!

Java - WeakHashMap

What is a WeakHashMap?

Imagine you're organizing a big party, and you have a guest list. But this isn't just any guest list – it's a magical list that automatically removes people who can't make it anymore. That's kind of what a WeakHashMap does in Java, but with objects instead of party guests!

A WeakHashMap is a special type of Map in Java that allows its keys to be garbage collected when they're no longer being used elsewhere in your program. This can be really useful when you want to create a cache that doesn't prevent objects from being cleaned up when they're no longer needed.

Class Declaration

Let's start by looking at how we declare a WeakHashMap:

import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(String[] args) {
        WeakHashMap<String, Integer> myWeakMap = new WeakHashMap<>();
    }
}

In this example, we're creating a WeakHashMap that uses String objects as keys and Integer objects as values. The <String, Integer> part is called "generics" – it's like telling Java what types of objects we want to store in our map.

Class Constructors

WeakHashMap comes with four different constructors. Let's look at each of them:

  1. Default constructor:

    WeakHashMap<String, Integer> map1 = new WeakHashMap<>();

    This creates an empty WeakHashMap with the default initial capacity (16) and load factor (0.75).

  2. Constructor with initial capacity:

    WeakHashMap<String, Integer> map2 = new WeakHashMap<>(100);

    This creates a WeakHashMap with the specified initial capacity and default load factor.

  3. Constructor with initial capacity and load factor:

    WeakHashMap<String, Integer> map3 = new WeakHashMap<>(100, 0.8f);

    This creates a WeakHashMap with the specified initial capacity and load factor.

  4. Constructor with another Map:

    Map<String, Integer> existingMap = new HashMap<>();
    existingMap.put("Alice", 25);
    existingMap.put("Bob", 30);
    WeakHashMap<String, Integer> map4 = new WeakHashMap<>(existingMap);

    This creates a WeakHashMap with the same mappings as the specified map.

Class Methods

WeakHashMap provides several methods for manipulating and accessing its contents. Here's a table of some of the most commonly used methods:

Method Description
put(K key, V value) Adds a key-value pair to the map
get(Object key) Retrieves the value associated with the specified key
remove(Object key) Removes the mapping for the specified key
size() Returns the number of key-value mappings in the map
clear() Removes all mappings from the map
containsKey(Object key) Returns true if the map contains the specified key
containsValue(Object value) Returns true if the map contains the specified value
isEmpty() Returns true if the map contains no key-value mappings

Let's see some of these methods in action:

WeakHashMap<String, Integer> ageMap = new WeakHashMap<>();

// Adding key-value pairs
ageMap.put("Alice", 25);
ageMap.put("Bob", 30);
ageMap.put("Charlie", 35);

// Retrieving a value
System.out.println("Alice's age: " + ageMap.get("Alice")); // Output: Alice's age: 25

// Checking if a key exists
System.out.println("Is David in the map? " + ageMap.containsKey("David")); // Output: Is David in the map? false

// Removing a key-value pair
ageMap.remove("Bob");
System.out.println("Map size after removing Bob: " + ageMap.size()); // Output: Map size after removing Bob: 2

// Clearing the map
ageMap.clear();
System.out.println("Is the map empty? " + ageMap.isEmpty()); // Output: Is the map empty? true

Methods Inherited

WeakHashMap inherits methods from its parent classes and interfaces. Here are some of the important inherited methods:

Inherited From Methods
java.util.AbstractMap clone(), equals(), hashCode(), toString()
java.util.Map entrySet(), keySet(), values()
java.lang.Object finalize(), getClass(), notify(), notifyAll(), wait()

Adding a Key-Value Pair to a WeakHashMap of Integer, Integer Pairs Example

Now, let's look at a more complete example of using a WeakHashMap with Integer keys and values:

import java.util.WeakHashMap;

public class WeakHashMapExample {
    public static void main(String[] args) {
        WeakHashMap<Integer, Integer> squareMap = new WeakHashMap<>();

        // Adding key-value pairs
        for (int i = 1; i <= 5; i++) {
            squareMap.put(i, i * i);
        }

        System.out.println("Initial map: " + squareMap);

        // Accessing values
        System.out.println("Square of 3: " + squareMap.get(3));

        // Removing a key-value pair
        squareMap.remove(2);
        System.out.println("Map after removing 2: " + squareMap);

        // Checking if a key exists
        System.out.println("Does map contain 4? " + squareMap.containsKey(4));

        // Checking if a value exists
        System.out.println("Does map contain value 16? " + squareMap.containsValue(16));

        // Iterating over the map
        System.out.println("Iterating over the map:");
        for (Integer key : squareMap.keySet()) {
            System.out.println("Key: " + key + ", Value: " + squareMap.get(key));
        }
    }
}

Output

When you run this code, you'll see output similar to this:

Initial map: {5=25, 4=16, 3=9, 2=4, 1=1}
Square of 3: 9
Map after removing 2: {5=25, 4=16, 3=9, 1=1}
Does map contain 4? true
Does map contain value 16? true
Iterating over the map:
Key: 5, Value: 25
Key: 4, Value: 16
Key: 3, Value: 9
Key: 1, Value: 1

And there you have it! You've just taken your first steps into the world of WeakHashMap in Java. Remember, the real power of WeakHashMap comes from its ability to allow keys to be garbage collected when they're no longer referenced elsewhere in your program. This can be incredibly useful in certain scenarios, like implementing caches or managing temporary data.

As you continue your Java journey, you'll discover more and more situations where WeakHashMap can be a valuable tool in your programming toolbox. Keep practicing, keep exploring, and most importantly, have fun coding!

Credits: Image by storyset