/*
* @Description TODO 重载equals方法,是为了二分查找时进行等价性比较
* @Date 11:52 2019/2/21
* @param null
* @return : null
**/
@Override
public boolean equals(Object obj) {
Student oth=(Student)obj; //强制类型转换
return this.name.equals(oth.name)&&
this.english==oth.english&&
this.math==oth.math;
}
}
/*
* @Description TODO 自定以比较器,实现Student对象首先按总成绩从低到高排序,
其次按名字排序(自小到大)。
* @Date 11:38 2019/2/21
**/
static Comparator<Student> comparator = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.total == o2.total) {
return o1.name.compareTo(o2.name);
}
//乘以-1是为了总成绩的从低到高排序
return Float.compare(o1.total, o2.total)*-1;
}
};
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 75, 80));
students.add(new Student("Tim", 85, 82));
students.add(new Student("Bob", 95, 60));
students.add(new Student("Alic", 63.5F, 88));
students.add(new Student("Candy", 75, 80));
System.out.println("after sorting:");
//使用自定义比较器排序
Collections.sort(students,comparator);
for(Student stu:students){
System.out.println(stu.toString());
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70