| Author |
unable to understand equals()
|
Phillipe Rodrigues
Ranch Hand
Joined: Oct 30, 2007
Posts: 165
|
|
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.
|
Thanks,
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10043
|
|
But what you posted IS an example... What exactly don't you understand - which part? Does this part make sense:
The equals() method in class Object uses only the == operator for comparisons
You HAVE to understand that first, and understand the difference between the == operator and the equals() method. So let's start there. If that much makes sense, we can discuss more. Otherwise, we need to stay here until that is clear.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Vinoth Thirunavukarasu
Ranch Hand
Joined: Dec 18, 2008
Posts: 164
|
|
|
First read the java Tutorial They explained in a detailed manner this will help you a lot in the beginning stage.
|
Java Best Practices
Linux Best Practices
Amortization Calculator
|
 |
 |
|
|
subject: unable to understand equals()
|
|
|