1) If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. 2) It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

a map supports searching on key fields [ something like the 'Pkey' jargon from the G'old database modelling days]. Many maps rely on hashing algorithms to provide efficient implementations.

so the more unique the 'Pkey' ,the better to search and find.

In a HashMap (or similar) all objects with the same hashcode are placed in the same bucket. If there's a single item in a bucket, that's the one you are looking for. If there are multiple items, equals() needs to be evoked as well on all of them until a match is found. This is potentially a lot slower (as the hashcode of items in a bucket is determined during insertion, so that lookup is VERY fast).

2 String objects with value "ABC" would return true to the equals method call. Let the hashcodes a=1, b=2, c=3, etc. So, the hashcodes for both the strings s1, and s2 would return 1+2+3 = 6. Simple!

Now, assuming you have 2 strings such that s1 = "ABC" and s2 = "BAC", then, the equals method returns false! However, the hashcode still returns the same value: for s1: 1+2+3 = 6 for s2: 2+1+3 = 6.

Hence, a smiple explanation by example to your statements.

I agree with Kosh's answer, plus I would like to add some more few things. If two objects are equal, let's say String a="abc" and String b="abc", then there must be a requirement that their hashcode must also be equal. But if they are not equal already, like in the Kosh's example above, you do not have to look for their hashcode results since the results might be equal or not equal. Under the condition that the objects are not equal to each other, if their hashcode results are equal, things might seem a little confusing. But expectation in this situation is that their hashcode shouldn't be equal normally(however this is NOT REQUIRED but since the objects are not equal, there is an expectation), so this may improve the performance of the hashtables. I hope I am thinking correct.. Make me correct please if not so.

--ugur<br />"Read,think, and ask. Learn the reason of living."