public class EmployeeSortTest {
public static void main(final String[] args) {
final Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);
Arrays.sort(staff);
for (final Employee e : staff) {
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}
}
class Employee implements Comparable<Employee> {
public Employee(final String n, final double s) {
name = n;
salary = s;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void raiseSalary(final double byPercent) {
final double raise = salary * byPercent / 100;
salary += raise;
}
@Override
public int compareTo(final Employee other) {
if (salary < other.salary) {
return -1;
}
if (salary > other.salary) {
return 1;
}
return 0;
}
private final String name;
private double salary;
}
我是 Java 的初学者,当我从 Cay S. Horstmann 先生和他的同事Core Java, Volume I: Fundamentals所写的书中学习时,我发现了一些我不太明白的东西。“employeesorttest.java”示例(第 245 页)。
我无法得到的是方法compareTo
。它如何改变输出?该方法只返回三个数字:0、-1 和 1。它没有改变任何位置或staff
. 另外,如果代码arrays.sort(staff)
确实有效,为什么我们还需要使用接口?
我知道这两个代码之间一定有一些关系。