Search code examples
javahashmapclone

Make obj and obj.clone() as same key in HashMap


Considering -

public class Class_A {
    // members ...
    @Override
    protected Object clone() throws CloneNotSupportedException {
        ...
    }
}

And

HashMap<Class_A, Integer> m_map = new HashMap<Class_A, Integer>(); 
Class_A a1 = new Class_A() ; 
Class_A a2 = (Class_A) a1.clone();
m_map.put(a1,6) ;

Now , what could be done in order that also m_map.get(a2) will return 6 as m_map.get(a1) ?


Solution

  • The location in the Map is found by using the object's hashCode and equals methods, so the correct thing to do is to override these methods in your Class_A such that a1.equals(a2) is true and a1.hashCode() == a2.hashCode().

    However, this rings something of an alarm bell in my mind. There's little reason to clone an immutable object, and Map keys should be immutable. See this question for the risks of mutable keys.