This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams and have Darcy DeClute on-line! See this thread for details.
To me, equals and compareTo both do the same basic job(comparing the objects) why does java have two different methods for doing the same work ( i know i am missing some thing here but want to know what).
some of my questions
1.) can one class have both equals and compareTo (if yes what is the use)
2.) which one is always better to use in a class, "equals" or "compareTo"
equals() checks if two objects are the same or not and returns a boolean.
compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is "less than", "equal to" or "greater than" the other. Not all objects can be logically ordered, so a compareTo() method doesn't always make sense.
Note that equals() doesn't define the ordering between objects, which compareTo() does.
2. Neither is better, it depends on what functionality your class needs.
- There is always an equals() method, because it's defined in Object. You only override it if you want different behaviour from the default (which is "are these refencing the same object?"). You don't always have a compareTo() method.
- If you do have a compareTo method, it is strongly recommended that you also provide an equals method that is consistent with it. That is, if a.compareTo(b) == 0, then a.equals(b) (and vice-versa).