2 回答

TA貢獻1780條經驗 獲得超5個贊
您的Pair
類應該實現Comparable<Pair<T, U>>
而不是Comparable<T, U>
,這是一種不存在的類型。您還應該確保T
和U
具有可比性。
界面中有很多有用的方法Comparator
可以幫助您比較事物。您可以使用它們來實現Comparable<Pair<T, U>>
.?事實上,您不需要實現Comparable
對列表進行排序。您只需要創建一個Comparator
!
以下是如何實施Comparable
:
class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {
? ? public int compare(final Pair<T, U> p1, final Pair<T, U> p2)
? ? {
? ? ? ? // this first compares the first field. If the first fields are the same, the second fields are compared
? ? ? ? // If you have a different requirement, implement it accordingly.
? ? ? ? return Comparator.comparing(Pair::getFirst).thenComparing(Pair::getSecond).compare(p1, p2);
? ? }
}
要對列表進行排序,請執行以下操作:
list.sort(Comparator.comparing(Pair::getFirst).thenComparing(Pair::getSecond));
要僅使用第二個字段對列表進行排序,請執行以下操作:
list.sort(Comparator.comparing(Pair::getSecond));

TA貢獻1831條經驗 獲得超4個贊
您應該確保您的T和U類型擴展Comparable并使您的Pair類實現Comparable<Pair<T,U>>:
public class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T,U>> {
private final T first;
private final U second;
public Pair(T first_, U second_) {
first = first_;
second = second_;}
public T getFirst() { return first; }
public U getSecond() { return second; }
@Override
public int compareTo(Pair<T, U> o) {
return this.second.compareTo(o.second);
}
}
添加回答
舉報