Java IdentityHashMap Real-Time Example

In this source code example, you will learn how to use the IdentityHashMap class in real-time Java projects.

Using Java IdentityHashMap to Track Object Metadata

The primary use case here is to store metadata or auxiliary information about distinct objects, even if their content might be the same. IdentityHashMap serves well for this purpose as it checks objects based on their references and not the content.

import java.util.IdentityHashMap;

class CustomObject {
    private String data;

    public CustomObject(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }
}

public class ObjectMetadataTracker {

    public static void main(String[] args) {
        // 1. Create a custom object and its duplicate using new keyword
        CustomObject object1 = new CustomObject("Hello");
        CustomObject object2 = new CustomObject("Hello");

        // 2. Create an `IdentityHashMap` to store metadata about objects
        IdentityHashMap<CustomObject, String> metadataMap = new IdentityHashMap<>();

        // 3. Add metadata to the `IdentityHashMap`
        metadataMap.put(object1, "Object 1 metadata");
        metadataMap.put(object2, "Object 2 metadata");

        // 4. Retrieve metadata for a specific object
        String object1Metadata = metadataMap.get(object1);
        System.out.println("Metadata for object1: " + object1Metadata);

        String object2Metadata = metadataMap.get(object2);
        System.out.println("Metadata for object2: " + object2Metadata);
    }
}

Output:

Metadata for object1: Object 1 metadata
Metadata for object2: Object 2 metadata

Explanation:

1. Created two CustomObject instances, object1 and object2, both holding the same string data "Hello". Though they have the same content, they are distinct objects in memory.

2. Initialized an IdentityHashMap named metadataMap to store metadata about different CustomObject instances.

3. Populated metadataMap with metadata for each CustomObject instance. The IdentityHashMap allows storing metadata for both object1 and object2 distinctly, even though their content is the same.

4. Demonstrated how to retrieve specific metadata for each object using the get() method.


Comments