java - 如何告诉 Java 接口(interface)实现了 Comparable?

标签 java class interface comparable

我有一个名为IDebt的接口(interface),以及一个实现名为Debt的接口(interface)的类。

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

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

Debt实现了Comparable,但是当我执行Collections.sort(debtList)时,我得到一个错误,因为Java无法知道实现IDebt的对象因此实现了 Comparable。

我该如何解决这个问题?

最佳答案

你可以这样做:

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;
        }
    });

关于java - 如何告诉 Java 接口(interface)实现了 Comparable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36924998/

相关文章:

java - 取消部署 mule 应用程序时如何停止 java 类

javascript - 如何在 addClass() 之后更改类的属性

c++ 在自定义异常的方法/构造函数签名中有和没有 throw()

c# - 向接口(interface)属性添加约束

c# - "Use of unassigned local variable"接口(interface)错误

java - Mongo的自增功能无法设置Long为_id?

java - 使用 Unsafe 从对象中提取数据(绕过 Security Manager0

java - ProGuard 警告 : there were 7 unresolved references to program class members

java - Home 与组件接口(interface) EJB

java - 在 onClickListener 中显示 Toast