Java中通过接口实现两个对象的比较,首先类要实现comparable接口,使用泛型规定了要进行比较的对象所属的类,而comparable接口的实现必须要定义的方法则是compareTo方法,在方法中传入此类的另一个对象,通过选定的成员变量与之比较,如果大于则返回1,小于返回-1,相等返回0.
例子代码:
package com.study.write;
import java.util.*;
public class EmployeeSortTest {
public static void main(String[] args) {
Employee2[] staff = new Employee2[3];
staff[0] = new Employee2("Harry", 35000);
staff[1] = new Employee2("Danny", 40000);
staff[2] = new Employee2("Tony", 20000);
Arrays.sort(staff);
//print out information about all Employee objects
for(Employee2 e:staff)
System.out.println("name = " + e.getName() +" " + "salary = " + e.getSalary());
}
}
class Employee2 implements Comparable<Employee2> {
public Employee2(String n, double s) {
name = n;
salary = s;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void raiseSalary(double byPecent) {
double raise = salary * byPecent / 100;
salary += raise;
}
/**compares employees by salary
@param other another Employee object
@return a negative value if this employee has a lower
salary than otherObject, 0 if the salaries are the same,
a positive value otherwise
*/
public int compareTo(Employee2 other) {
if(salary < other.salary) return -1;
if(salary > other.salary) return 1;
return 0;
}
private String name;
private double salary;
}