The Java comparator has two classes, namely the comparable interface and the comparator interface.
The comparer has a very large effect when sorting an array of objects
1, using the comparable interface, you need to rewrite the compareTo(T o) method, where the collation is defined, you can directly call Java.util.Arrays.sort () to sort the array of objects,
Example:
Package com.yaoxun.test;
public class Student implements comparable<student> {
private int score;
private int age;
@Override public
int compareTo (Student o) {
if (This.score > O.score) return
1;
else if (This.score < o.score)
return-1;
else {
if (This.age > O.age) return
1;
else if (This.age < o.age)
return-1;
else return
0;}}}
2, using the comparator interface, you need to rewrite the compare(t O1, T O2) method,
Package edu.sjtu.ist.comutil;
Import Java.util.Comparator;
Class Student {private String name;
private int age;
private float score;
Public Student (String name, int age, float score) {this.name = name;
This.age = age;
This.score = score;
Public String GetName () {return name;
public void SetName (String name) {this.name = name;
public int getage () {return age;
public void Setage (int age) {this.age = age;
public float Getscore () {return score;
public void SetScore (float score) {this.score = score;
Public String toString () {return name+ "\t\t" +age+ "\t\t" +score; Class Studentcomparator implements comparator<student>{@Override public int compare (Student O1, Stud
ent O2) {//TODO auto-generated Method stub if (O1.getscore () >o2.getscore ()) return-1; else if (O1.getscore () <o2.getscore ()) return 1;
else{if (O1.getage () >o2.getage ()) return 1;
else if (O1.getage () <o2.getage ()) return-1;
else return 0; }
}
}