Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new to java - how to write compareTo method for sorting

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

like image 345
user3240944 Avatar asked Nov 29 '25 20:11

user3240944


1 Answers

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 javadocs
  • Java generics tutorial
like image 54
rgettman Avatar answered Dec 02 '25 09:12

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!