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;
運作結果為: