【问题标题】:How do I tell Java that an interface implements Comparable?我如何告诉 Java 接口实现了 Comparable?
【发布时间】:2016-04-28 20:36:34
【问题描述】:

我有一个名为 IDebt 的接口,以及一个实现上述接口的名为 Debt 的类。

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

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

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

我该如何解决这个问题?

【问题讨论】:

  • 你不能。您的List 可能包含SpiderDept,而implements 不包含任何内容...
  • 所有IDebts 是否都旨在与所有其他IDebts 相媲美? (特别是,两个不同实现的实例是否应该相互比较?)
  • 查看断线答案。 TLDR:让 IDebt 扩展 Comparable 接口。

标签: java class interface comparable


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 接下来的问题是如何与不同的对象进行比较。
  • 您可以使用实际的比较器进行排序,我通常这样做,我会更新我的答案
【解决方案2】:

让你的IDept接口扩展Comparable

interface IDept extends Comparable{
    ....
}

接口可以扩展其他接口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-03-17
    相关资源
    最近更新 更多