我試圖讓一個實用程序的方法簽名正確,以便我可以擺脫一些未檢查類型鑄造。到目前爲止,我有:java泛型擴展和列表
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()方法進行簽名的各種更改,但似乎無法獲得正確的語法,因此我可以傳入特定類型的動物,並在沒有類型安全問題的情況下返回相同的動物。
任何幫助,非常感謝!
我想你需要一個通用的方法,這樣可以明確的預期收益類型,喜歡這裏:HTTP:/ /stackoverflow.com/questions/590405/generic-method-in-java-without-generic-argument – mellamokb 2012-07-30 22:00:04