What's the reasoning behind decision to include these methods in the java.lang.Object? Equality and hashing doesn't make sense for many classes.
It would be more logical to make two interfaces:
interface Equalable {
boolean equals(Equalable other);
}
interface Hashable extends Equalable {
int hashCode();
}
For example HashSet definition might look like
class HashSet<T extends Hashable> ...
It would prevent one of the common beginner mistakes - using set of items without implementing equals/hashCode.
(Personally, if they were in an interface, I'd put them both in there to avoid at least one class of
equals
/hashCode
mistakes.)I think you'd want an implementation in Object, as a fall-back mechanism, meaning everything would have an implementation anyway, interface or not.
I suspect a lot of it is historical; programming Java today looks quite a bit different than programming Java back then did.
Really, it's just for convenience, and it's better this way. Well, think about what it would take to do object equality if you didn't have the .equals method:
This is true even for a hashCode. Sometimes reference equality is enough. If you made HashSet only accept objects that implement Hashable, then you'd have to explicitly make your classes Hashable, even though you only want reference equality. And you've reduced the universality of an otherwise great data structure.
It's better to have Object have a default (and sometimes sufficient) .equals and .hashCode function and cause a few problems for new comers, than to make frequent users of the language trudge through more red tape.
Its a generic implementation. You are supposed to override the implementation if you need them. Otherwise you have a reasonable default implementation.
At least the equals is a must have. Creating interfaces for basic operations probably would involve to much overhead.