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 uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?