Skip to content
Advertisement

How can UserDefined class be a key of hashmap if hashCode() & equals() return same value

I am trying to implement HashMap with UserDefined class as Key, i am successfull even when I implement both hashCode() (returns 0 for every object) & equals() (returns false for every object). My Code

public class UserDefinedMapKey {

    public static void main(String[] args) {
        HashMap<Beck, Integer> hm = new HashMap<Beck, Integer>();
        hm.put(new Beck(10,"archit"), 20);
        hm.put(new Beck(10,"archit"), 30);
        hm.put(new Beck(30,"goel"), 50);
        
        for(Map.Entry<Beck, Integer> m : hm.entrySet()) {
            System.out.println(m.getKey() + "===" + m.getValue());
        }
    }
    
}`
`

class Beck {
    int arc;
    String grc;
    
    public Beck(int i, String string) {
        // TODO Auto-generated constructor stub
    }
    public int getArc() {
        return arc;
    }
    public void setArc(int arc) {
        this.arc = arc;
    }
    public String getGrc() {
        return grc;
    }
    public void setGrc(String grc) {
        this.grc = grc;
    }
    
    @Override
    public int hashCode() {
        return 0;
    }
    
    @Override
    public boolean equals(Object b) {
        return false;
    }
    
}

output:-

main.java.Interview.Beck@0===20
main.java.Interview.Beck@0===30
main.java.Interview.Beck@0===50

Can anyone let me know the reason how it’s working

Advertisement

Answer

This is happening because equals is returning false. The equals/hashCode contract is completely broken. There is no assertion that if two objects are the same, they are equal. Two objects can have the same hashcode and still not be equal.

What is occurring is that on the 2nd and 3rd put call, there is a check to see if any objects in the given bucket (defined by hashCode) are the same. They are not because equals returns false, so the new object is added to the same bucket.

You need to properly implement the contract properly for it to work properly.

Baeldung tutorial on equals/hashcode contract.

Advertisement