假设下面的泛型类有 2 个类型 T, U
public class Pair<T, U> implements Comparable<T, U> { //Error 1
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; }
}
及其项目列表
List<Pair<Integer, Integer>> = new ArrayList<>()
需要根据第一个/第二个属性进行排序。不幸的是,类定义包含一些问题,出现以下错误:
Error 1: wrong number of type arguments
如何设计比较器类?这段代码可能是完全错误的
public class SortBySecond implements Comparable <Pair <T, U>> {
public int compare(final Pair<T, U> p1, final Pair<T, U> p2) //Error 2
{
return t1.getSecond().compareTo(t2.getSecond()); //Updated comparator
}
}
Error 2 : Can not find symbols T, U, V
感谢您的帮助。
最佳答案
你的 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));
关于Java:对具有两种类型的泛型类进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57913205/