Java: if I overwrite the .equals method, can I check for test equality with ==?
I have the following situation: I need to sort trees by height, so I made the Tree comparable using the height attribute. However, I also had to overwrite the equals and hashCode methods to avoid unpredictable behavior.
However, sometimes I may need to compare root references or something along those lines using ==. Is this still possible, or is the comparison call == equal to the equals method?
a source to share
equals()
designed to compare an object with the rules set by the programmer. In your example, you are comparing your trees by height, so you would write equals()
to have it compare heights.
==
as you said compares links. They are neither affected equals()
nor hashCode()
. This way you will not change your behavior.
a source to share
Overriding the equals () method will have no effect on the == operator. == is used to check if 2 references point to the same object. The equals () method "meaningfully" compares 2 objects.
It is important to realize that the work here is "meaningful". Equality is easier to understand when you are comparing, for example, 2 strings or 2 integers. Therefore, the equals () method inherited from the Object class has already been overridden by the String and Wrapper classes (Integer, Float, etc.). However, what if you are comparing 2 Song objects. Here equality can be established based on 1) Artist name
2) Song title
3) or some other criterion
Therefore, you must override the equals () method to "explicitly" determine "when" the 2 song objects are considered equal.
The "unpredictable behavior" you mentioned in your question refers to objects like the one above (song) when dealing with collections like Map. You MUST NOT use these objects in the map until you override equals () and hashcode (). The reason is in how hashmap search and indexing works. Refer to JavaDoc for specific rules. What you need to remember:
If 2 objects are significantly equal, their hash code must return the same value. However, the 2 objects are not required to be equal if they return the same hashcode. Again, Java doesn't enforce any rules regarding this. You are responsible for using the equals () and hashcode () methods correctly.
a source to share
I think this raises a more important question: is it advisable to match these objects on comparable objects. It might be more appropriate to use Comparator for operations that work at altitude rather than embedding ordinal computations in the class itself.
My general philosophy on this is only to implement Comparable if there is a truly natural ordering for the object. In the case of a tree node, is height the only way anyone could ever want to sort? Maybe this is a private class and the answer is yes. But even then, creating a Comparator isn't a lot of extra work, and it leaves things flexible if you decide you want to make that node tree a protected or public class some day.
a source to share