The equals method of Object just compare address:
public boolean equals(Object obj) {
return (this == obj);
}
I think it's not useful in most cases, and we may override it. But for the most Classes I developed, I didn't override the equals method, because I won't use it at all...
So I just wonder, why Java language designer put equals method in Object?
Why there isn't an "Equalable" interface like Comparable?
Identity provides a universal definition of equality. Every object is equal to itself. It may or may not be logically equal to some objects that are not itself. If it is, override equals and hashCode. If not, inherit the Object ones.
That is very different from being Comparable. It is possible for a structure that might be represented by a class to lack any meaningful total order - consider the complex numbers.
The equals() method is used by the Java system classes, for example in HashMap. Since every object may be stored in HashMap, every object needs an equals() method. The default implementation is sufficient for this.
This is just one example. There are lots of places equals() is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With