Could someone please explaine me what's going on in this code snippet:
posted 10 years ago
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