Java IdentityHashMap Methods Example

In this source code example, we will show you the usage of important Java IdentityHashMap class methods with examples.

IdentityHashMap is a specialized implementation of the Map interface from java.util package. Unlike standard implementations like HashMap, which uses the equals() method for comparisons, IdentityHashMap uses reference equality (==) in place of object equality (equals()) when comparing keys (and values).

Java IdentityHashMap Common Methods

import java.util.IdentityHashMap;

public class IdentityHashMapMethods {

    public static void main(String[] args) {
        // 1. Create an `IdentityHashMap`
        IdentityHashMap<String, String> identityMap = new IdentityHashMap<>();

        // 2. Add entries to the `IdentityHashMap`
        String key1 = new String("One");
        String key2 = new String("One");
        identityMap.put(key1, "First");
        identityMap.put(key2, "First Duplicate");
        System.out.println("2. IdentityHashMap content: " + identityMap);

        // 3. Check if a key is present
        boolean hasKeyOne = identityMap.containsKey(key1);
        System.out.println("3. Contains key 'One'? " + hasKeyOne);

        // 4. Get a value using its key
        String valueOfOne = identityMap.get(key1);
        System.out.println("4. Value for key 'One': " + valueOfOne);

        // 5. Remove an entry using its key
        identityMap.remove(key1);
        System.out.println("5. IdentityHashMap after removing key 'One': " + identityMap);

        // 6. Check the size of the IdentityHashMap
        int size = identityMap.size();
        System.out.println("6. Size of the IdentityHashMap: " + size);
    }
}

Output:

2. IdentityHashMap content: {One=First, One=First Duplicate}
3. Contains key 'One'? true
4. Value for key 'One': First
5. IdentityHashMap after removing key 'One': {One=First Duplicate}
6. Size of the IdentityHashMap: 1

Explanation:

1. Initialized an IdentityHashMap named identityMap.

2. Added key-value pairs using the put() method. Note that IdentityHashMap uses reference-equality in place of object-equality when comparing keys (and values). Thus, two separate String objects with the same content are considered distinct keys.

3. Checked the presence of a specific key with the containsKey() method.

4. Retrieved the value associated with a particular key using the get() method.

5. Removed a key-value pair using the remove() method.

6. Checked the number of key-value pairs using the size() method.

The primary characteristic of an IdentityHashMap is that it uses reference equality (==) when comparing keys and values, unlike the standard HashMap that uses object equality (equals() method).


Comments