Two Laptop Bag
The moose likes Beginning Java and the fly likes unable to understand equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "unable to understand equals() " Watch "unable to understand equals() " New topic

unable to understand equals()

Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
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.

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
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

I agree. Here's the link:
subject: unable to understand equals()
It's not a secret anymore!