Repository navigation
Expand file tree
/
Copy pathShowComparator.java
More file actions
97 lines (85 loc) · 2.65 KB
/
Copy pathShowComparator.java
File metadata and controls
97 lines (85 loc) · 2.65 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
package Novice_class;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class ShowComparator {
static class Student {
// 属性
String name;
int age;
int id;
// 方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
// 构造器
public Student() {
}
public Student(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
}
// age小的放在前面
static class IdComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if (o1.age < o2.age) {
return -1;
} else if (o1.age > o2.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] + " ");
}
}
public static void printArray2(Student[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int[] array = {1, 5, 3, 7, 2, 9, 6, 4, 1, 5};
printArray(array);
Arrays.sort(array);
System.out.println();
printArray(array);
Student s1 = new Student("张三", 1, 20);
Student s2 = new Student("李四", 2, 23);
Student s3 = new Student("王五", 3, 17);
Student s4 = new Student("老六", 4, 52);
Student s5 = new Student("哈奇", 5, 34);
Student[] students = {s1, s2, s3, s4, s5};
System.out.println("-------------------");
printArray2(students);
System.out.println();
Arrays.sort(students, new IdComparator());
printArray2(students);
System.out.println("----------------");
ArrayList<Student> arrayList = new ArrayList<>();
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
arrayList.add(s5);
for (Student s : arrayList) {
System.out.println(s);
}
arrayList.sort(new IdComparator());
System.out.println("-------------------------");
for (Student s : arrayList) {
System.out.println(s);
}
}
}