Example of IdentityHashMap in Java

By Arvind Rai, November 12, 2023
java.util.IdentityHashMap is almost same as java.util.HashMap except that the IdentityHashMap checks duplicate keys only on the basis of reference value. In HashMap, duplicate key is checked by overriding hashCode and equals but IdentityHashMap differs in this context. It breaks intentionally the contract of Map.
In the below example we have a bean which overrides hashCode and equals that checks duplicate on the name property. We will add element in IdentityHashMap by duplicate key and check the size. Result will be that size will increase because IdentityHashMap checks duplicate key only on reference basis.
IdentityHashMapDemo.java
package com.concretepage.util;
import java.util.IdentityHashMap;
import java.util.Map;

public class IdentityHashMapDemo {
    public static void main(String[] args) {
        Map<Bean,String> imap = new IdentityHashMap<Bean,String>();
        Bean b1 = new Bean("A");
        Bean b2 = new Bean("B");
        Bean b3 = new Bean("C");
        Bean b4 = new Bean("C");
        imap.put(b1, "A");
        imap.put(b2, "B");
        imap.put(b3, "C");
        System.out.println(imap.size());
        imap.put(b4, "D");
        System.out.println(imap.size());
    }
}
class Bean {
    public String name;

    public Bean(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        return name.equals(((Bean)o).name);
    }
    @Override
    public int hashCode() {
        int hash = 13;
        hash = (31 * hash) + (null == name ? 0 : name.hashCode());
        return hash;
    }
}
Output
3
4 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us