簡體   English   中英

通過泛型限制類型參數

[英]Restrict type parameter by means of generics

給定卡路里接口和實現的類

// Interface that defines that item has calories and may be compared by it

interface Calorie extends Comparable<Calorie> {
  public int compareTo(Calorie object);
  public int getCalories();
}

// Examples of classes CaloryGrader is supposed to work with
class Drink implements Calorie {
    // Some implemenation...
}

class Bakery implements Calorie {
    // Some implementation...
}

class Cake extends Bakery {
    // Some implementation...
}


## Given CaloryGrader class where I need to implement sorted static "grade" method ##

class CaloryGrader {

    /**
     * Returns sorted in ascending order copy of items list.
     * 
     * Sort order is defined by item calories.
     *
     * @param items collection of items to sort
     * @return sorted copy
     */

    public List grade(List items) {
        // Add implementation
    }

}

任務是 - 通過泛型編寫成績,以便僅對包含卡路里及其子類的項目列表進行排序。

我寫了以下等級方法的簽名

  public static <T extends Calorie> List<T> grade(List<T> items) {

不過,它不起作用,我無法弄清楚原因。

T是一種方法可以接受的項目List是方法的返回類型

我假設參數List將限制List,它只能傳遞給方法的所有子類卡路里。 但現在不正確。

我可以創建一個原始類型列表並將其傳遞給該方法。 我認為這是因為它轉換為List並且它適合。

解決方案不應該是將原始類型傳遞給方法並收到編譯時錯誤。 我想我想念一些東西。

你可以使用一個數組來表示這個硬約束:grade(T [] items)

最重要的是,一個數組支持List來快速轉換來回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM