pembed2003 wrote:
> The program prints out 2 lines which I am not sure I understand. My P
> class has a hashCode method which simply returns the id of the object.
> I put 2 'new P(1)' instance into m but why doesn't HashMap reject the
> second one or overwrite the first one becasue they have the same hash
> code??? I though the purpose of hashCode is to let you reject or
> detect dup objects, no?
That's not really true. The purpose of the hash code is as a *hint* to let the
implementation find object that are equal. It would be perfectly possible to
write a conforming implementation that didn't actually use the hash code at
all, but just looped through the collection trying equals() on everything.
(That implementation would be too slow for general use, but would probably be
more efficient for very small collections)
The real implementation does make use of the hash code and it depends crucially
on the assumptions that if two object have different hash codes then they are
not equal(), and that if they *are* equal then they have the same hash codes.
What it does *not* require is that two object with the same hash code are
equal(). In fact it is perfectly legal for *every* object to have the same
hash code (33, say). That would make hashed collections very inefficient, but
they'd still work correctly.
In your example code you *seem* to be correctly implementing hashCode() and
equals() to work together in the way that hashed collections require, but
actually there's a small bug

Your definition of equals() takes a P as
parameter, and so it doesn't override the definition in Object (which takes an
Object parameter). Hence the HashMap is using your definition of hashCode(),
but the definition of equals() from Object (which uses identity comparison).
So it doesn't quite work...
-- chris