Why equals and hashCode were defined in Object?

前端 未结 10 1211
天命终不由人
天命终不由人 2020-12-06 05:50

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 l

10条回答
  •  暖寄归人
    2020-12-06 06:04

    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.

提交回复
热议问题