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?
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18327)
- How to add BASIC Authentication into HttpURLConnection?(16085)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)