2

The following two questions were asked recently and marked as potential duplicates of each other:

  1. Java: why is there a Comparator interface but no Hasher and Equator?
  2. Why is .compareTo() in an interface while .equals() is in a class in Java?

Given the short time between the questions and very similar subject matter, are these questions duplicates of each other? If so which is the "canonical" question and which is the duplicate?

3

I voted no, they are not duplicates.

They are two separate questions, deserving two separate answers.

  • Q: Why there is an interface for Comparing object, but not one for Hashing or Equals?

    Answer:

    Equality is a property of two objects, but in OO, you always call a method on one single object, and that object gets to solely decide how to handle that method call.

    So, in a design like Java's, where equality is a property of one of the two objects being compared, it isn't even possible to guarantee some basic properties of equality such as symmetry (a == b <=> b == a), because in the first case, the method is being called on a and in the second case it is being called on b and due to the basic principles of OO, it is solely a's decision (in the first case) or b's decision (in the second case) whether or not it considers itself equal to the other one.

  • Question: What is the reason behind behind putting .compareTo() in the interface and .equals() in the class?

    Answer :

    Not all objects can be compared, but all objects can be checked for equality.
    ...
    The Object contract applies to all Java classes. If even one class cannot be compared to other instances of its own class, then Object cannot require it to be part of the interface.

I'd leave them linked with a comment, but I would not close either as a duplicate to the other. The accepted answers in both specifically address the question that was asked, and are different enough that I would prefer to see them as separate.

  • 2
    I agree. Even if closely related, they are slightly different. You actually quoted my answer on one of them, which does not really apply to the other question. – user22815 Jun 5 '15 at 15:10

You must log in to answer this question.