package Comparable;
import java.util.*;
/**
*
* @author cmx
*/
public class Diaoyong
{
public static void main(String [] args)
{
TestComparableInterface[] staff=new TestComparableInterface[3];
staff[2]=new TestComparableInterface("1 ",101);
staff[0]=new TestComparableInterface("2 ",202);
staff[1]=new TestComparableInterface("3 ",303);
for(TestComparableInterface e:staff)
{
System.out.println(e.getName()+" "+e.getSalary());
}
System.out.println("--------调用后-------");
Arrays.sort(staff);
for(TestComparableInterface e:staff)
{
System.out.println(e.getName()+" "+e.getSalary());
}
}
}
package Comparable;
/**
*以下是类,而不是调用
* @author cmx
*/
public class TestComparableInterface implements Comparable<TestComparableInterface>
{
private double salary;
private String name;
public TestComparableInterface(String name,double salary)
{
this.salary=salary;
this.name=name;
}
public double getSalary()
{
return this.salary;
}
public String getName()
{
return name;
}
public int compareTo(TestComparableInterface other)
{
return Double.compare(this.salary, other.salary);
}
}
//误区:对于Arrays.sort()为标准库中的内容,其实现依赖于标准库中的Comparable接口,这个接口不可以重载,所以不可以使用自定义的接口(如下)。如果非要使用也可以,但是就不可以使用Arrays.sort()了
package Comparable;
/**
*
* @author cmx
*/
public interface Comparable_Define<T>
{
public int compareTo(T other);
}
/*
如果本文第二块代码块的首部改为
public class TestComparableInterface implements Comparable_Define<TestComparableInterface>
就不可以编译正确了
*/