-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComparator1.java
More file actions
83 lines (67 loc) · 2.3 KB
/
Copy pathComparator1.java
File metadata and controls
83 lines (67 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.Arrays;
import java.util.Comparator;
public class Comparator1 {
public static class Student {
public String name;
public int id;
public int age;
public Student (String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
public static class IdAscendingComprator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.id - o2.id;
// 等价于:
// if (o1.id < o2.id) {
// return -1;
// }
// else if (o1.id > o2.id) {
// return 1;
// }
// else {return 0;}
}
}
public static class IdDescendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.id - o1.id;
}
}
public static class AgeAscendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
}
public static class AgeDescendingComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o2.age - o1.age;
}
}
public static void printStudents(Student[] students) {
for (Student student : students) {
System.out.println("Name: " + student.name + " Id: " + student.id + " Age: "+ student.age);
}
System.out.println("====================================");
}
public static void main(String[] args) {
Student s1 = new Student("A", 1, 23);
Student s2 = new Student("B", 2, 21);
Student s3 = new Student("C", 3, 22);
Student[] students = new Student[] {s1, s2, s3};
printStudents(students);
Arrays.sort(students, new IdAscendingComprator());
printStudents((students));
Arrays.sort(students, new IdDescendingComparator());
printStudents(students);
Arrays.sort(students, new AgeAscendingComparator());
printStudents(students);
Arrays.sort(students, new AgeDescendingComparator());
printStudents(students);
}
}