Hi,
I'm new to java.I'm reading SCJP1.5 by Kathy.
Please help me in understanding the below with an example
The equals() method in class Object uses only the == operator for comparisons,
so unless you override equals(), two objects are considered equal only if the two
references refer to the same object.
Let's look at what it means to not be able to use an object as a hashtable key.
Imagine you have a car, a very specific car (say, John's red Subaru Outback as
opposed to Mary's purple Mini) that you want to put in a HashMap (a type of
hashtable we'll look at later in this chapter), so that you can search on a particular
car and retrieve the corresponding Person object that represents the owner. So you
add the car instance as the key to the HashMap (along with a corresponding Person
object as the value). But now what happens when you want to do a search? You want
to say to the HashMap collection, "Here's the car, now give me the Person object
that goes with this car." But now you're in trouble unless you still have a reference
to the exact object you used as the key when you added it to the Collection. In other
words, you can't make an identical Car object and use it for the search.
The bottom line is this: if you want objects of your class to be used as keys for a
hashtable (or as elements in any data structure that uses equivalency for searching
for�and/or retrieving�an object), then you must override equals() so that two
different instances can be considered the same.