forked from algorithmzuo/algorithm-primary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShowComparator.java
More file actions
106 lines (90 loc) · 2.56 KB
/
ShowComparator.java
File metadata and controls
106 lines (90 loc) · 2.56 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package class06;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class ShowComparator {
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;
}
}
// 谁id大,谁放前!
public static class IdComparator implements Comparator<Student> {
// 如果返回负数,认为第一个参数应该排在前面
// 如果返回正数,认为第二个参数应该排在前面
// 如果返回0,认为谁放前面无所谓
@Override
public int compare(Student o1, Student o2) {
if (o1.id < o2.id) {
return 1;
} else if (o2.id < o1.id) {
return -1;
} else {
return 0;
}
}
}
// 谁age大,谁放前!
public static class AgeComparator implements Comparator<Student> {
// 如果返回负数,认为第一个参数应该排在前面
// 如果返回正数,认为第二个参数应该排在前面
// 如果返回0,认为谁放前面无所谓
@Override
public int compare(Student o1, Student o2) {
if (o1.age < o2.age) {
return 1;
} else if (o2.age < o1.age) {
return -1;
} else {
return 0;
}
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void printStudents(Student[] students) {
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].name + ", " + students[i].id + ", " + students[i].age);
}
}
public static void main(String[] args) {
int[] arr = { 8, 1, 4, 1, 6, 8, 4, 1, 5, 8, 2, 3, 0 };
printArray(arr);
Arrays.sort(arr);
printArray(arr);
Student s1 = new Student("张三", 5, 27);
Student s2 = new Student("李四", 1, 17);
Student s3 = new Student("王五", 4, 29);
Student s4 = new Student("赵六", 3, 9);
Student s5 = new Student("左七", 2, 34);
Student[] students = { s1, s2, s3, s4, s5 };
printStudents(students);
System.out.println("=======");
Arrays.sort(students, new IdComparator());
printStudents(students);
System.out.println("=======");
ArrayList<Student> arrList = new ArrayList<>();
arrList.add(s1);
arrList.add(s2);
arrList.add(s3);
arrList.add(s4);
arrList.add(s5);
for (Student s : arrList) {
System.out.println(s.name + ", " + s.id + ", " + s.age);
}
System.out.println("=======");
arrList.sort(new AgeComparator());
for (Student s : arrList) {
System.out.println(s.name + ", " + s.id + ", " + s.age);
}
}
}