Tuesday, March 29, 2011

What It Means If You Don't Override equals() Methods

What It Means If You Don't Override equals():
if you don't override a class's equals()
method, you won't be able to use those objects as a key in a hashtable and you
probably won't get accurate Sets, such that there are no conceptual duplicates.

Remember that the equals(), hashCode(), and toString() methods are
all public. The following would not be a valid override of the equals() method, although
it might appear to be if you don’t look closely enough during the exam:
class Foo { boolean equals(Object o) { } }
And watch out for the argument types as well. The following method is an
overload, but not an override of the equals() method:
class Boo { public boolean equals(Boo b) { } }

Collections such as HashMap and
HashSet use the hashcode value of an object to determine how the object should
be stored in the collection, and the hashcode is used again to help locate the object
in the collection.

In real-life hashing, it’s not uncommon to have more than one entry in a
bucket. Hashing retrieval is a two-step process.
1. Find the right bucket (using hashCode())
2. Search the bucket for the right element (using equals() ).

No comments:

Post a Comment