If two objects have the same hash code, but not equal, can they exist simultaneously in the HashMap?
----answer is yes.
Reason:
In HashMap, because key can not be duplicated, he judged the key is not repeated when the hashcode this method, but also used the Equals method.
It is not possible to repeat here that equals and hashcode as long as there is a range.
When we add an element to a set, HashMap, HashSet, Hashtable collection, the collection first calls the Hashcode method of the object, This allows you to directly locate the location where it is stored, and if there are no other elements, save it directly. If there is already an element there, call the Equals method to match whether the two elements are the same, the same is not present, and the difference is hashed to a different location Second, hashcode important? For a list collection, an array, he is a burden, not important, but for HashMap, HashSet, Hashtable, it becomes extremely important. |
Test code:
Packagecom.rainy.test;ImportJava.util.HashSet;ImportJava.util.Set; Public classApp { Public Static voidMain (string[] args) {Set<A> set =NewHashset<a>(); A A1=NewA (); A A2=NewA (); a1.a= "1"; a2.a= "2"; Set.add (A1); Set.add (A2); for(A a:set) {System.out.println (A.A); } }}classA { PublicString A; @Override Public Booleanequals (Object obj) {A Obja=(A) obj; return This. A.equals (OBJA.A); } @Override Public inthashcode () {return1; } }
Code results:
2
1
If two objects have the same hash code, but not equal, can they exist simultaneously in the HashMap?