[英]How do I tell Java that an interface implements Comparable?
我有一个名为IDebt的接口,以及一个实现名为Debt的接口的类。
我还有一个由实现IDebt接口的对象组成的列表:
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;
}
});
让你的IDept
接口扩展Comparable
interface IDept extends Comparable{
....
}
接口可以扩展其他接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.