亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java:對具有兩種類型的泛型類進行排序

Java:對具有兩種類型的泛型類進行排序

RISEBY 2023-07-28 10:04:19
假設以下泛型類具有 2 種類型 T、Upublic 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感謝您的幫助。
查看完整描述

2 回答

?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

您的Pair類應該實現Comparable<Pair<T, U>>而不是Comparable<T, U>,這是一種不存在的類型。您還應該確保TU具有可比性。

界面中有很多有用的方法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));


查看完整回答
反對 回復 2023-07-28
?
慕容708150

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

        }

}


查看完整回答
反對 回復 2023-07-28
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號