Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there isn't an "Equalable" interface in Java? [duplicate]

Tags:

java

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?

like image 713
Sayakiss Avatar asked Feb 23 '26 23:02

Sayakiss


2 Answers

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.

like image 110
Patricia Shanahan Avatar answered Feb 26 '26 12:02

Patricia Shanahan


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.

like image 35
Thomas Stets Avatar answered Feb 26 '26 11:02

Thomas Stets