import java.util.*;
public class CompType implements Comparable{
int i;
int j;
public CompType(int n1,int n2){
i = n1;
j = n2;
}
public String toString(){
return "[i = "+i+ ", j = "+j+ "] ";
}
public int compareTo(Object rv){
int rvi = ((CompType)rv).i;
int rvj = ((CompType)rv).j;
return (i <rvi ? -1 : (i==rvi ? 0:1));
}
}
这个就是只比较第一个元素的大小!
public class EmployeeSortTest
{
public static void main(String[] args)
{
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);
// print out information about all Employee objects
for (int i = 0;i <staff.length;i++)
{
Employee e=staff[i];
System.out.println( "name= " + e.getName() + ",salary= " + e.getSalary());
}
}
}
class Employee implements Comparable
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public int compareTo(Object otherObject)
{
Employee other = (Employee)otherObject;
if (salary < other.salary) return -1;
if (salary > other.salary) return 1;
return 0;
}