Comparable
Comparable是排序接口,一个类实现了Comparable接口,则该类支持排序。若存在“实现Comparable接口的类的对象的集合(或数组)”,则该集合(或数组)可以通过Collections.sort(或Arrays.sort)进行排序。
Comparable定义
public interface Comparable<T> {
public int compareTo(T o);
}
实现Comparable接口的类需要重写compareTo()方法,对象就可以比较大小。
x.compareTo(y)
来“比较x和y的大小”。可以理解为return x - y
public static void main(String[] args) {
int[] arr = {2, 1, 9, 5};
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public class Student implements Comparable<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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
/*
* 重写compareTo()方法,自定义排序规则
* */
@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;
}
}
}
public class Test {
public static void main(String[] args) {
Student stu[] = {new Student("zhangsan",20,90.0f),
new Student("lisi",22,90.0f),
new Student("wangwu",20,99.0f),
new Student("sunliu",22,100.0f)};
Arrays.sort(stu);
for (Student s : stu){
System.out.println(s);
}
}
}
Comparator
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
import java.util.Comparator;
public class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
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;
}
}
}
public class Test {
public static void main(String[] args) {
Student stu[] = {new Student("zhangsan",20,90.0f),
new Student("lisi",22,90.0f),
new Student("wangwu",20,99.0f),
new Student("sunliu",22,100.0f)};
// Arrays.sort(stu);
Arrays.sort(stu, new StudentComparator());
for (Student s : stu){
System.out.println(s);
}
}
}