New to java - how to write compareTo method for sorting

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; // 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 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.

+3
source share
2 answers

, Comparable.

implements Comparable

compareTo . Comparable Java 1.4, . Comparable ( - ).

implements Comparable<Student1>

compareTo . Generics , compareTo.

, , .

+4

, . compareTo . compareTo(Object another) , :

, ; , ; 0, , .

, , , , Integer.compare(age, another.age), . , , .

0

All Articles