MCPcopy Create free account
hub / github.com/algorithmzuo/algorithm-journey / main

Method main

src/class026/Code03_Comparator.java:33–94  ·  view source on GitHub ↗
(String[] args)

Source from the content-addressed store, hash-verified

31 }
32
33 public static void main(String[] args) {
34 Employee s1 = new Employee(2, 27);
35 Employee s2 = new Employee(1, 60);
36 Employee s3 = new Employee(4, 19);
37 Employee s4 = new Employee(3, 23);
38 Employee s5 = new Employee(1, 35);
39 Employee s6 = new Employee(3, 55);
40 Employee[] arr = { s1, s2, s3, s4, s5, s6 };
41 Arrays.sort(arr, new EmployeeComparator());
42 for (Employee e : arr) {
43 System.out.println(e.company + " , " + e.age);
44 }
45
46 System.out.println("=====");
47
48 Arrays.sort(arr, (a, b) -> b.age - a.age);
49 for (Employee e : arr) {
50 System.out.println(e.company + " , " + e.age);
51 }
52
53 System.out.println("=====");
54 // 所有员工,先按照谁的公司编号小,谁在前;如果公司编号一样,谁年龄小谁在前
55 Arrays.sort(arr, (a, b) -> a.company != b.company ? (a.company - b.company) : (a.age - b.age));
56 for (Employee e : arr) {
57 System.out.println(e.company + " , " + e.age);
58 }
59
60 TreeSet<Employee> treeSet1 = new TreeSet<>(new EmployeeComparator());
61 for (Employee e : arr) {
62 treeSet1.add(e);
63 }
64 System.out.println(treeSet1.size());
65
66 // 会去重
67 treeSet1.add(new Employee(2, 27));
68 System.out.println(treeSet1.size());
69
70 System.out.println("===");
71
72 // 如果不想去重,就需要增加更多的比较
73 // 比如对象的内存地址、或者如果对象有数组下标之类的独特信息
74 TreeSet<Employee> treeSet2 = new TreeSet<>((a, b) -> a.company != b.company ? (a.company - b.company)
75 : a.age != b.age ? (a.age - b.age) : a.toString().compareTo(b.toString()));
76 for (Employee e : arr) {
77 treeSet2.add(e);
78 }
79 System.out.println(treeSet2.size());
80
81 // 不会去重
82 treeSet2.add(new Employee(2, 27));
83 System.out.println(treeSet2.size());
84
85 System.out.println("===");
86
87 // PriorityQueue不会去重,不再展示了
88
89 // 字典序
90 String str1 = "abcde";

Callers

nothing calls this directly

Calls 5

toStringMethod · 0.80
sortMethod · 0.45
printlnMethod · 0.45
addMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected