File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes method equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "method equals" Watch "method equals" New topic

method equals

Vlada Den
Ranch Hand

Joined: Dec 19, 2004
Posts: 32
Hey guys,

Could someone please explaine me what's going on in this code snippet:

Thank you,

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The equals() method tells us if two objects are equal in some way that you get to define. This one says two CarBeans should be considered equal if they have matching RegNo fields.

To compare two objects you ask one to compare itself to the other. So we'd write

if ( carBean1.equals( carBean2 ) ) ...

In the line above we know we have two CarBean objects. But some generic tools like Set and HashMap need to test any kind of objects to be equal. To make the equals method work for them, the designers made the argument to the method an Object. So we could get any kind of object passed in there and we need the first test in your method: if "other" is not the same class it cannot be equal.

if ( carBean1.equals( aBanana ) ) // false!

After that we cast the other to our own class and compare registry numbers. Some classes have to check a bunch of fields to decide if they are equal, like all the parts of a name or address so this part can be longer.

Does that help? If so, look into compareTo() and see how it works.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
It is sorta covered in the JavaRanch Style Guide.
subject: method equals
jQuery in Action, 3rd edition