I have been going through some tutorials on how to sort an object based on one if its properties. For example, if we have a class called person which has a property called name, we simply implement Comparable interface and override compareTo.
However, different tutorials show different code which you write inside compareTo, for example here is one way:
public int compareTo(Object o) throws ClassCastException {
Date d = (Date)o; // If this doesn't work, ClassCastException is thrown
int yd = year - d.year;
int md = month - d.month;
int dd = day - d.day;
if (yd != 0) return yd;
else if (md != 0) return md;
else return dd;
}
but yet here is different way to write the compareTo method:
@Override
public int compareTo(Student1 o) {
return Integer.compare(grade, o.grade);
}
as a result I am totally confused as to what algorithm or formula is required to write a proper compareTo
It all depends on how the interface Comparable is implemented.
If in the class you see
implements Comparable
then the first compareTo method is correct. This was the way to implement Comparable through Java 1.4, the last version before generics was introduced. It's implementing the raw interface Comparable (without any generics).
If in the class you see
implements Comparable<Student1>
then the second compareTo method is correct. Generics helps in this case by supplying the type of the parameter in the compareTo method.
Both are right, but the first one is obsolete and the second one is now favored.
Comparable javadocsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With