Effective Java --Comparable接口

compareTo方法是Comparable接口的唯一方法。类实现了Comparable接口,表明它的实例具有内在的排序关系。

自己实现compareTo方法应该注意的点:

自反性: x.compareTo(x) == 0

可传递性: x.compareTo(y)>0 && y.compareTo(z)>0 ==> x.compareTo(z) > 0

可逆性: x.compareTo(y) == -y.compareTo(x)

建议: (x.compareTo(y) == 0) == x.equals(y)

例子:

public class ComparableImpl  implements Comparable<ComparableImpl>{

    public static void main(String[] args) {

        ComparableImpl A = new ComparableImpl("A",9);
ComparableImpl B = new ComparableImpl("B",5);
ComparableImpl C = new ComparableImpl("B",3); //TreeSet 去重 排序
TreeSet set = new TreeSet();
set.add(A);
set.add(B);
set.add(C); while(!set .isEmpty()){
System.out.println(set.pollFirst());
}
} private String name;
private Integer age; public int getAge() {
return age;
}
public String getName() {
return name;
} public ComparableImpl(String name , int age)
{
this.name = name;
this.age = age;
} @Override
public int compareTo(ComparableImpl o) {
return this.name.compareTo(o.getName()) == 0 ? this.age.compareTo(o.getAge()) : this.name.compareTo(o.getName());
} @Override
public String toString() {
return "ComparableImpl{" +"name='" + name + '\'' +", age=" + age +'}';
}
} 运行结果:

ComparableImpl{name='A', age=9}
ComparableImpl{name='B', age=3}
ComparableImpl{name='B', age=5}

05-11 11:26