FAQ

Java

JSP

Servlet


Advertisement



Why equals() can be true even if it's comparing two different objects?

This question comes from a SCJP mock question, "What two statements are true about properly overridden hashCode and equals() method?" The the correct answers are "hashCode() can always return the same value, regardless of the object that invoked it" and "equals() can be true even if it?s comparing different objects".

The first statement, "hashCode() can always return the same value, regardless of the object that invoked it" is easy to understand. Because the hashCode() method always returns the hash of the instance of the object, the caller of the method doesn't matter. But why "equals() can be true even if it's comparing different objects"?

Every object has an instance method equals() inherited from the class Object. The default implementation of equals() in Object returns true only if you have references to the same object.

However, every time when you create a Class, you can override the equals() method to define the way that your class object should equal. A good example is the String class. Its equals() method is overridden so that the equals() method returns true when two String have the same values, not necessary when the two Strings objects are assigned with the same object reference. In other words, the logic of the equals() method is totally up to the coder who creates the Class, as long as it returns a boolean. So "equals() can be true even if it?s comparing different objects" if it's so defined.

Note, when you override the equals() method, you'd also override the hashcode() method. See Why always override hashcode() if overriding equals()? for more information.

You may also find this FAQ useful: What are the differences between the equality operator and the equals method?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |