猿问

Java:对具有两种类型的泛型类进行排序

假设以下泛型类具有 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

感谢您的帮助。


RISEBY
浏览 108回答 2
2回答

翻阅古今

您的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));

慕容708150

您应该确保您的T和U类型扩展Comparable并使您的Pair类实现Comparable<Pair<T,U>>:public class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T,U>>&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; private final T first;&nbsp; &nbsp; &nbsp; &nbsp; private final U second;&nbsp; &nbsp; &nbsp; &nbsp; public Pair(T first_, U second_) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; first = first_;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; second = second_;}&nbsp; &nbsp; &nbsp; &nbsp; public T getFirst() { return first; }&nbsp; &nbsp; &nbsp; &nbsp; public U getSecond() { return second; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public int compareTo(Pair<T, U> o) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.second.compareTo(o.second);&nbsp; &nbsp; &nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答