Why equals and hashCode were defined in Object?

2019-01-14 22:40发布

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.

9条回答
手持菜刀,她持情操
2楼-- · 2019-01-14 22:54

(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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-14 22:56

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:

AreEqual(Object obj1,Object obj2) {
  if(!obj1 instanceof Equalable) return false;
  if(!obj2 instanceof Equalable) return false;
  return ((Equalable)(obj1).equals((Equalable)obj2);
}

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.

查看更多
够拽才男人
4楼-- · 2019-01-14 22:59

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.

查看更多
登录 后发表回答