-1

What does this means:

public int hashCode() {
       return HashCodeBuilder.reflectionHashCode(this);
}

Please can anybody explain me above code?

Alex
  • 11,115
  • 12
  • 51
  • 64
  • possible duplicate of [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – Medo42 Sep 09 '14 at 10:15

2 Answers2

3

hashCode is a fast way to determine whether two things are unequal: if they have different hashCodes. So if you have a class Book with i.a. a field ISBN, then you may define an equals on the ISBN code, and hashCode can be the hashCode of the ISBN value.

HashCodeBuilder is a utility that makes a hash code of all fields, a bit too much. But that will find equal objects.

Not definining a hashCode will default to the Object.hashCode, and mostly two "equal" object will still have different hash codes, making them useless.

Data structures like HashMap and HashSet use hashCode to speed up things tremendously. Different hashCodes then imply different objects. Equal hashCodes still means that .equals has to be tested.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

Its an integer representation of your object instance. Two equal object must have same hashCodes, however it can happen, that 2 unequal objects can have same hashCodes. Its important to implement when you're using your objects in data structures like, Maps, Sets, because under the hood they use hashCodes to put the object in the right place.

If you don't implement it, the default implementation inherited from Object class is to use references, so 2 objects will have same hashcodes only if they are the same objects (e.g. x == y).

So if you would not implement hashCode() and you would add this object to Map, it would work, however would be extremely uneficient (O(n)), on the other hand with perfect hashing algorithm it would be close to O(1).

Tomas Bartalos
  • 1,256
  • 12
  • 29