Implementing equals method using compareTo

徘徊边缘 提交于 2019-11-30 18:03:27

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.

compareTo may involve a lot more work than is necessary just to get an equality answer, which may end up being a performance issue, depending on your application usage.

Other than that, following DRY principles it would be a good idea to re-use the code as you have suggested.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!