Implementing equals method using compareTo

前端 未结 2 1105
温柔的废话
温柔的废话 2021-01-02 01:57

General question: When implementing an override of the default equals method in Java, what concerns should I have about simply utilizing an already implemented

2条回答
  •  萌比男神i
    2021-01-02 02:34

    The difference between equals() and compareTo() is that equals() just checks if two objects are equal to each other where the compareTo() is used to identify the natural order of the instances of specified class. Also equals() method has a contract with hashCode() method but compareTo() hasn't.

    According to JavaDoc:

    Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

    It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

    You can feel free to reuse compareTo() method logic in your equals() method but keep in mind all the contracts to the equals(), hashCode() and contract from JavaDoc for compareTo() method. If they do not conflict with each other then go ahead.

    I think that the enforcement of contracts is more important point.

提交回复
热议问题