3
package test;

import java.util.HashMap;

public class test {
    public static void main(String args[]) {
        HashMap<ID, String> h = new HashMap<ID, String> ();
        String b;

        ID id1 = new ID(100);
        ID id2 = new ID(200);
        ID id3 = new ID(200);

        h.put(id1, "apple");
        h.put(id2, "pear");

        **System.out.println(h.containsKey(id3));**
    }
}

class ID {
    Integer code;

    public ID(Integer id) {
        this.code = id;
    }

    @Override
    public int hashCode()
    {
        return code.hashCode();
    }

    @Override
    public boolean equals(Object o)
    {
        return this.code.equals(o);
    }
}

the output of this program is "false". I can't understand of this result. I implemented hashCode and equals which are overrided. I don't have an idea how to solve. How to use objects as keys in java HashMap?

1
  • @saka1029 He puts another ID instance with the same integer value. So it should print "true" if he fixes his problem in the equals method. Commented Jun 6, 2015 at 10:36

2 Answers 2

7

Your equals implementation is wrong :

public boolean equals(Object o)
{
    return this.code.equals(o); // this will never return true,
                                // since you are comparing an Integer instance
                                // to an ID instance
}

You should compare this code to the other code:

public boolean equals(Object o)
{
    if (!(o instanceof ID))
        return false;
    ID oid = (ID) o;
    return this.code.equals(oid.code);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Wrong Implementation of equals method. According to your implementation it executes the Integer class equals method. We should handle the logic without execute library classes equals methods.

@Override 
public boolean equals(Object o) {
    if (o == null || ((o instanceof ID) && o.hashCode() != this.hashCode())) {
        return false;
    }
    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.