Can anybody explain me the difference between hashCode() and equals() methods. I have read it from book but not quiet clear how to use them in programs. If possible please give some example also. How hashCode() comes in picture while working with == and equals() methods.
If two instances have the same value, we expect them to to be equals, but they should also have the same hash value.
A hash value is like a quick-lookup version of the value of the instance. If they are equal then they must have the same hash value, but having the same hash value doesn't necessarily mean they are equal.
HashMaps use this 'quick lookup' property of Objects create fast storage. Provided the Class implementation behaves responsibly, an instance can be found in constant time, regardless of the size of the HashMap. This is pretty impressive considering there may be millions, 10's, 100's of millions or billions of objects in the hashMap.
It does this by looking for the 'hash' value, and then finding whether the retrieved instances is 'equals' as a second step. Using only equals would require looking at every one of the billion items.