What does this means:
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
Please can anybody explain me above code?
What does this means:
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
Please can anybody explain me above code?
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.
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).