1. 问题
2. 解答
- 当需要排序的集合不是单纯的数字类型时,通常可以使用 Comparable 接口以简单的方式实现对象排序或自定义排序;
- Comparable 接口内部有一个要重写的关键方法 compareTo(Object o),用于比较两个对象的大小,返回一个整数;
- 例如在 x.compareTo(y) 中,x=y 返回 0,x<y 返回小于 0 的值,x>y 返回大于0的值;
- 因此可以对实现了 Comparable 接口的类的对象进行排序;
- 应用如下:
import java.util.ArrayList;
import java.util.Collections;
class User implements Comparable<User> {
private Integer id;
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
'}';
}
@Override
public int compareTo(User o) {
if (this.id > o.getId()) {
return 1;
} else if (this.id < o.getId()) {
return -1;
} else {
return 0;
}
}
}
public class Test {
public static void main(String[] args) {
ArrayList<User> al = new ArrayList();
al.add(new User(3));
al.add(new User(5));
al.add(new User(4));
System.out.println(al);
Collections.sort(al);
System.out.println(al);
}
}