What I understand
If the return value is 0, then there is nothing to do. If it is -1, then the two values will be swept. If we want to change the order (asc/desc), just change the comparison operators.
What I found on the websites
The return value will be -1, 0 or 1 as the first argument is less than, equal to, or greater than the second.
What I want to know
Why do we need the return value 1? I tested my program without return value 1 and it sort correctly.
The following program sort students objects by grade with ascending order. If the sorting order is wanted to change, change the comparison operator.
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Student s1 = new Student("JJJ", 5);
Student s2 = new Student("DDD", 2);
Student s3 = new Student("RRR", 4);
Student s4 = new Student("CCC", 4);
Student s5 = new Student("GGG", 3);
Student s6 = new Student("JJJ", 1);
List < Student > ls = new ArrayList < > ();
ls.add(s1);
ls.add(s2);
ls.add(s3);
ls.add(s4);
ls.add(s5);
ls.add(s6);
for (Student s: ls) {
s.print();
}
System.out.println("=====================");
ls.sort(new Comparator < Student > () {
@Override
public int compare(Student s1, Student s2) {
if (s1.grade < s2.grade) return -1;
// else if (s1.grade > s2.grade) return 1;
else return 0;
}
});
for (Student s: ls) {
s.print();
}
}
public static void printLs(List < Student > ls) {
for (Student s: ls) {
s.print();
}
}
}
class Student {
String name;
int grade;
Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
void print() {
System.out.println(this.name + " - " + this.grade);
}
}