Java的Comparable接口

  Comparable接口提供比较对象大小功能,实现了此接口的类的对象比较大小将通过接口提供的compareTo方法。

  此方法的返回int类型,分三种情况。

  • 返回正数,当前对象大于目标对象
  • 返回负数,当前对象小于目标对象
  • 返回0,当前对象等于目标对象

  TreeSet提供了将对象排序功能(默认升序排序),如果存储容器的是自定义类,那此类将要实现Comparable功能以供TreeSet进行对象大小比较时使用,否则将报错。

  

public class TestCompareTo implements Comparable<TestCompareTo> {
    private Integer a = null;

    public TestCompareTo(Integer a) {
        this.a = a;
    }

    public Integer getA() {
        return a;
    }

    @Override
    public int compareTo(TestCompareTo o) {
        return this.a > o.a ? -1 : (this.a == o.a ? 0 : 1);
    }

}
public class Test{
    public static void main(String[] args) {
        //test TreeSet
        Set<TestCompareTo> set = new TreeSet<>();
        set.add(new TestCompareTo(-10));
        set.add(new TestCompareTo(-20));
        set.add(new TestCompareTo(-30));
        set.add(new TestCompareTo(0));
        set.add(new TestCompareTo(10));
        set.add(new TestCompareTo(-100));
        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            TestCompareTo tmp = (TestCompareTo) iterator.next();
            System.out.println(tmp.getA());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/chiweiming/p/11843056.html