0

I have a class myDemoClass to store name and a class to put in a HashMap. While experimenting with overriding hashCode() method, the HashMap is returning null even if hashcodes are different. Why? I have overridden the hashCode() method so that different objects will have different hashcode even if having the same name value.

public class myDemoClass {

    String name;
    int value;
    static int i=1;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int hashCode()
    {
        //return name.hashCode();//now the hashcode are same
        return i++;//now the hashcode is different
    }

    public boolean equals(Object obj)
    {
        myDemoClass m=(myDemoClass)obj;
        if(obj==this)
            return true;

        if(obj instanceof myDemoClass)
        {
            return getName().equals(m.getName());
        }

        return false;
    }

}

public class Hashcodes {

    myDemoClass m1=new myDemoClass();
    myDemoClass m2=new myDemoClass();

    HashMap h=new HashMap();

    public boolean test()
    {
        m1.setName("s");
        m2.setName("s");
        System.out.println(m1.hashCode());
        System.out.println(m2.hashCode());

        h.put(m1, "a1");
        h.put(m1, "b1");

        System.out.println(h.get(m1));
        System.out.println(h.get(m2));
        System.out.println(h.get(m1));

        return true;
    }

    public static void main(String args[])
    {
        Hashcodes h=new Hashcodes();
        h.test();
    }

}

Output with different hashcode:

1
2
null
null
null

Output with same hashcode:

115
115
b1
b1
b1

2 Answers 2

1

Notice that you made your hashCode() function return a static field that gets incremented every time that hashCode() is called. This is causing the hash code to be different each time it is called, even for the same object!

For example, say you have the following code:

MyDemoClass m1 = new MyDemoClass();
m1.hashCode();
m1.hashCode();

The first call to hashCode() returns 1, then the static field was incremented to 2. The next call to hashCode() returns 2, which wasn't the same as the one before. Since the objects aren't keeping track of their personal hash code and refer to the same static field every time, your objects never return the same hash code, and your HashMap will always return a null value.

Sign up to request clarification or add additional context in comments.

Comments

0

I agree with the above answer, using static field for calculating hashCode of an object is bad practice. Please consider using only non static fields , in your case - what is wrong in performing :
public int hashCode() { return name.hashCode() * 31 + (new Integer(value)).hashCode(); }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.