[Java] 纯文本查看 复制代码
// Comparable 比较示例
// 定义一个Student类,实现Comparable接口并重写compareTo方法
public class Student implements Comparable<Student> {
private String id;
private String username;
private Integer age;
// 省略了 set and get
public int compareTo(Student o) {
if (this.age > o.getAge()) {
return 1;
} else if (this.age < o.getAge()) {
return -1;
} else {
return 0;
}
}
}
[Java] 纯文本查看 复制代码
// 测试类 (测试Comparable比较器)
public class Test1 {
public static void main(String[] args) {
Student[] stu = new Student[3];
stu[0] = new Student("1", "zhangsan", 11);
stu[1] = new Student("2", "lisi", 15);
stu[2] = new Student("3", "wangwu", 13);
Arrays.sort(stu);
for (int i = 0; i < stu.length; i++) {
System.out.println(stu.getId() + " "
+ stu.getUsername()
+ " " + stu.getAge());
}
}
}
[Java] 纯文本查看 复制代码
// Comparator 比较示例
public class Test2 {
public static void main(String[] args) {
List<Student> stus = new ArrayList<>();
stus.add(new Student("1", "zhengsan", 11));
stus.add(new Student("2", "lisi", 15));
stus.add(new Student("3", "wangwu", 13));
Collections.sort(stus, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
}
});
stus.forEach((Student stu) -> {
System.out.println(stu.getId() + " " + stu.getUsername() + " " + stu.getAge());
});
}
}