[英]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.