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》中学习时,我发现了一些我不太清楚的东西理解。 第 245 页上的“employeesorttest.java”示例。
我无法得到的是方法compareTo
。它如何改变输出?该方法仅返回三个数字:0、-1 和 1。它没有更改 staff
中的任何位置或对象。另外,如果代码 arrays.sort(staff)
确实有效,为什么我们还需要使用该接口(interface)?
我知道这两个代码之间一定存在某种关系。
最佳答案
Comparable 接口(interface)仅告诉其他代码该元素应相对于另一个元素排序。由调用代码实际使用该信息执行某些操作。
可比较的用途包括:
请参阅Object Ordering Java Tutorial 中的部分了解更多信息。
关于java - 我可以忽略 "comparable"的使用吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10333780/