sabaTEL.net

Java, MySQL, Avaya

What it means if you don’t override equals()

If you don’t override a class’s equals() method, you won’t be able to use those objects as a key in a hashtable and you probably won’t get accurate Sets, such that there are no conceptual duplicates.

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.

Note the there are 2 things to be done in order to make a valid equality comparison.

  • Be sure that the object being tested is the correct type. It comes in polymorphically as type Object, so you need to do an instanceof test on it. Having two objects of different class types be considered equal is usually not a good idea.
  • Compare the attributes we care about (in this case, just moofValue)

Only the developer can decide what makes two instances equal. (For best performance, you’re going to want to check the fewer number of attributes.)

equals(), hashCode() and toString() methods are all public. The following would not be a valid override of the equals() method:

Remember to check the argument types as well, the following method is an overload, but not an override of the equals() method:

Advertisements

June 30, 2013 - Posted by | Java

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: