簡體   English   中英

java泛型擴展和列表

[英]java generics extension and lists

我正在嘗試在實用程序上使方法簽名正確,以便我可以擺脫一些未經檢查的類型轉換。 到目前為止,我有:

public interface Animal {
public long getNumberLegs();
public int getWeight();
}

public class Cat implements Animal {
public long getNumberLegs() { return 4; }
public int getWeight() { return 10; }
}

public class Tuple<X, Y> {
public final X x;
public final Y y;

public Tuple(X x, Y y) {
    this.x = x;
    this.y = y;
}
}

public class AnimalUtils {
public static Tuple<List<? extends Animal>, Long> getAnimalsWithTotalWeightUnder100(List<? extends Animal> beans) {
    int totalWeight = 0;
    List<Animal> resultSet = new ArrayList<Animal>();
    //...returns a sublist of Animals that weight less than 100 and return the weight of all animals together.
        return new Tuple<List<? extends Animal>, Long>(resultSet, totalWeight);     
}
}

現在我試着打個電話:

Collection animals = // contains a list of cats
Tuple<List<? extends Animal>, Long> result = AnimalUtils.getAnimalsWithTotalWeightUnder100(animals);
Collection<Cat> cats = result.x;  //unchecked cast…how can i get rid of this?

我的想法是,我可以通過傳遞適當的動物清單來重復使用這種實用方法檢查狗,老鼠等。 我嘗試對getAnimalsWithTotalWeightUnder100()方法的簽名進行各種更改,但似乎無法使語法正確,以便我可以傳入特定類型的動物並讓它返回相同而不會出現類型安全問題。

任何幫助是極大的贊賞!

如果內存服務,你需要使方法本身通用,如下所示:

public <T extends Animal> static Tuple<List<T>, Long> getAnimalsWithTotalWeightUnder100(List<T> beans) {

暫無
暫無

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

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