java - HashMap returning null even though hashCode/equals are overriden -
i have hashmap maps custom object tokendocumentpair double. tokendocumentpair follows:
static class tokendocumentpair { int documentnum; string token; public tokendocumentpair(string token, int documentnum) { this.token = token; this.documentnum = documentnum; } public boolean equals(tokendocumentpair other) { return (this.documentnum == other.documentnum && this.token.equals(other.token)); } public int hashcode() { int result = 1; result = 37 * result + objects.hashcode(this.documentnum); result = 37 * result + objects.hashcode(this.token); return result; } public string tostring() { return string.format("[document #%s, token: %s]", documentnum, token); } } the problem is, when create tokendocumentpair pair1 = new tokendocumentpair("hello", 1) , store hashmap<tokendocumentpair, double> map, , try fetch tokendocumentpair pair2 = new tokendocumentpair("hello", 1), returns null. however, under impression since hashcode , equals method match , based on 2 fields stored, hash map able find original pair1 , return value me.
tokendocumentpair pair1 = new tokendocumentpair("hello", 1); tokendocumentpair pair2 = new tokendocumentpair("hello", 1); assert pair1.hashcode() == pair2.hashcode(); // ok assert pair1.equals(pair2); // ok hashmap<tokendocumentpair, double> map = new hashmap<>(); map.put(pair1, 0.0); map.get(pair2); // null map.containskey(pair2); // false what doing wrong here?
equals method not overridden. have overloaded it.
signature of method object#equals override must this:
@override public boolean equals(object o) { //... } in order make sure you're overriding method, use @override annotation when declaring method. if add annotation current equals method, compiler error , proper error message.
Comments
Post a Comment