如何告诉Java接口实现Comparable?

时间:2016-04-28 20:36:34

标签: java class interface comparable

我有一个名为 IDebt 的接口,以及一个实现名为债务的接口的类。

我还有一个由实现IDebt接口的对象组成的列表:

List<IDebt> debtList = new ArrayList<IDebt>();

Debt 实现Comparable,但是当我执行 Collections.sort(debtList)时出现错误,因为Java无法知道实现IDebt的对象就像这样实现可比较。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

public static interface MyInterface extends Comparable<MyInterface> {

}

public static class MyClass implements MyInterface {

    @Override
    public int compareTo(MyInterface another) {
        return 0; //write a comparison method here
    }
}

然后

List<MyInterface> test = new ArrayList<>();
Collections.sort(test);

将起作用

更新:也可以进行排序,这可能更有意义:

Collections.sort(test, new Comparator<MyInterface >() {
        @Override
        public int compare(MyInterface lhs, MyInterface rhs) {
            return 0;
        }
    });

答案 1 :(得分:0)

使IDept界面扩展Comparable

interface IDept extends Comparable{
    ....
}

接口可以扩展其他接口。