Justin's Words

Java Comparator

上代码:

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
package co.young.ComparatorExample;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Comparator;

public class ComparableExample {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee( "harry Hacker" , 35000 );
staff[1] = new Employee( "carl cracke" , 75000 );
staff[2] = new Employee( "tony Tester" , 38000 );
Arrays.sort(staff);

System.out.println("As Arrays: ");
for (Employee e: staff)
System.out.println(e.toString());

ArrayList<Employee> staffList = new ArrayList<>();
staffList.add(new Employee( "harry Hacker" , 35000 ));
staffList.add(new Employee( "carl cracke" , 75000 ));
staffList.add(new Employee( "tony Tester" , 38000 ));
Collections.sort(staffList, new CustomComparator());

System.out.println("As ArrayList: ");
for (Employee e: staffList) {
System.out.println(e.toString());
}
}
}

class Employee implements Comparable<Employee> {
private int id;
private String name;
private double salary;

public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
Random ID = new Random();
id = ID.nextInt(10000000);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}

public int compareTo(Employee other) {
if (salary < other.salary)
return - 1 ;
if (salary > other.salary)
return 1 ;
return 0 ;
}

@Override
public String toString() {
return "id=" + getId() + " name=" + getName() + ".salary=" + getSalary();
}
}

class CustomComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.compareTo(e2);
}
}

输出:

1
2
3
4
5
6
7
8
As Arrays:
id = 187862 name = "harry Hacker" salary = 35000.0
id = 4744557 name = "tony Tester" salary = 38000.0
id = 2432769 name = "carl cracke" salary = 75000.0
As ArrayList:
id = 9443980 name = "harry Hacker" salary = 35000.0
id = 6015335 name = "tony Tester" salary = 38000.0
id = 9993145 name = "carl cracke" salary = 75000.0