Java how does HashMap identify the key object if hashCode are the same and equals is true? -
i thought hat hashmap identifying keys using hascode , equals. code still not give me value back. missing?
import java.util.hashmap; import java.util.map; /** * created kic on 25.04.15. */ public class typepair { private final class a; private final class b; public typepair(class a, class b) { this.a = a; this.b = b; } public typepair(object a, object b) { this.a = a.getclass(); this.b = b.getclass(); } public boolean ispair (object a, object b) { return this.a.isassignablefrom(a.getclass()) && this.b.isassignablefrom(b.getclass()); } @override public boolean equals(object obj) { if (obj instanceof typepair) { return a.isassignablefrom(((typepair) obj).a) && b.isassignablefrom(((typepair) obj).b); } else { return false; } } @override public int hashcode() { return 1; } public static void main(string[] args) { typepair = new typepair(number.class, string.class); typepair b = new typepair(12, "hello"); map<typepair, boolean> test = new hashmap<>(); test.put(a, true); system.out.println(a.hashcode() == b.hashcode()); system.out.println(a.equals(b)); system.out.println("und? " + test.get(a)); system.out.println("und? " + test.get(b)); } }
this code prints:
true true und? true und? null
your implementation of equals()
violating contract (it not symmetric), that's why not work correctly.
you need use like:
@override public boolean equals(object obj) { if (obj instanceof typepair) { typepair objtypepair = (typepair) obj; return .isassignablefrom(objtypepair.a) && b .isassignablefrom(objtypepair.b) || objtypepair.a.isassignablefrom(a) && objtypepair.b.isassignablefrom(b); } else { return false; } }
Comments
Post a Comment