I learned some lessons on how to sort an object based on one, if its properties. For example, if we have a class called a person that has a property called a name, we simply implement the Comparable interface and override compareTo.
However, different manuals show different code that you write inside compareTo, for example, here one way :
public int compareTo(Object o) throws ClassCastException {
Date d = (Date)o;
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 here is another way to write compareTo method:
@Override
public int compareTo(Student1 o) {
return Integer.compare(grade, o.grade);
}
As a result, I am completely confused by what algorithm or formula is required to write the correct comparison.
source
share