0

Currently I drilled into the JSE source code for fun. From some tutorials I found a principle two equals objects (i.e. as to object a and b a.equals(b) returns true) must have the same hashcode, on the other hand, two objects with the same hashcode are not necessarily equals. According to the HashTable source code of Java API (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java), e.g. refer to line 254, we can almost derive equals => same hashcode, but I still can not fully understand why two objects with the same hashcode are not necessarily equals. Anyone can give more reasoning on this? Thanks in advance

Note! This question is more interested in why two objects with the same hash code are not necessarily equals

Rui
  • 3,454
  • 6
  • 37
  • 70

1 Answers1

1

That's a simple matter of counting. A hash code is an integer so has 32 bits. Take now a Long for example. Since it is 64 bits long, there are much more values than 232. Hence there must be a lot of values having the same hash code.

Henry
  • 42,982
  • 7
  • 68
  • 84