Using objects as keys in Java HashMap
•
Java
package test;
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 the program is false I can't understand the result I implemented hashcode and equals, which are overwritten I don't know how to solve it How to use objects as keys in Java HashMap?
Solution
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 with other codes:
public boolean equals(Object o) { if (!(o instanceof ID)) return false; ID oid = (ID) o; return this.code.equals(oid.code); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码