[英]How do I tell Java that an interface implements Comparable?
I have an interface named IDebt , and a class implementing said interface named Debt . 我有一个名为IDebt的接口,以及一个实现名为Debt的接口的类。
I also have a list made of objects implementing the IDebt interface: 我还有一个由实现IDebt接口的对象组成的列表:
List<IDebt> debtList = new ArrayList<IDebt>();
The class Debt implements Comparable, but when I do Collections.sort(debtList) I get an error, because Java has no way to know that the object implementing IDebt as such implements Comparable. Debt类实现Comparable,但是当我执行Collections.sort(debtList)时遇到错误,因为Java无法知道实现IDebt的对象实现Comparable。
How can I solve this? 我该如何解决?
You can do this: 你可以这样做:
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
}
}
Then 然后
List<MyInterface> test = new ArrayList<>();
Collections.sort(test);
will work 将工作
Update: also for sorting maybe this makes more sense: 更新:对于排序也可能更有意义:
Collections.sort(test, new Comparator<MyInterface >() {
@Override
public int compare(MyInterface lhs, MyInterface rhs) {
return 0;
}
});
Make your IDept
interface extend Comparable
让你的
IDept
接口扩展Comparable
interface IDept extends Comparable{
....
}
Interfaces can extend other Interfaces. 接口可以扩展其他接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.