Searching...
Tuesday, 13 August 2013

IdentityHashMap Example

05:34

In Normal HashMap checks the duplicate key via hashcode and equals methods of an object but in the case of java.util.IdentityHashMap checks duplicate keys only on the basis of reference value.this class is designed for use only in the rare cases wherein reference-equality semantics are required.

In the below example HashMap is checking the duplicate key based on the person name and it is avoiding the duplicate but in the case of IdentityHashMap it is checking the reference-equality during the insertion.

 

package com.vinod.test.core;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class IdentityHashMapExample {
    public static void main(String[] args) {
        Person h1 = new Person("Vinod");
        Person h2 = new Person("Raj");
        Person h3 = new Person("Raghav");
        Person h4 = new Person("Raghav");

        System.out.println("From HashMap");
        Map<Person, String> hmap = new HashMap<Person, String>();
        hmap.put(h1, "Bangalore");
        hmap.put(h2, "Bangalore");
        hmap.put(h3, "Chennai");

        System.out.println(hmap.size());
        hmap.put(h4, "Hydrabad");
        System.out.println(hmap.size());

        System.out.println("From IdentityHashMap");
        Map<Person, String> imap = new IdentityHashMap<Person, String>();
        imap.put(h1, "Bangalore");
        imap.put(h2, "Bangalore");
        imap.put(h3, "Chennai");
        System.out.println(imap.size());
        imap.put(h4, "Hydrabad");
        System.out.println(imap.size());
    }
}

class Person {
    public String name;
    public Person(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        return name.equals(((Person) o).name);
    }
    @Override
    public int hashCode() {
        int hash = 13;
        hash = (31 * hash) + (null == name ? 0 : name.hashCode());
        return hash;
    }
}

 

Output

 

From HashMap
3
3
From IdentityHashMap
3
4

Reference

 

http://docs.oracle.com/javase/7/docs/api/java/util/IdentityHashMap.html

0 comments: