Two Laptop Bag*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "method equals" Watch "method equals" New topic
Author

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,

Vlada
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: method equals
 
Similar Threads
Problem with using a bean in JSP [Solved]
equals() , instanceof
Using the equals method
Equals method.
Doubt in K&B SCJP 5: Using Maps