2012-07-30 56 views
0

我試圖讓一個實用程序的方法簽名正確,以便我可以擺脫一些未檢查類型鑄造。到目前爲止,我有: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()方法進行簽名的各種更改,但似乎無法獲得正確的語法,因此我可以傳入特定類型的動物,並在沒有類型安全問題的情況下返回相同的動物。

任何幫助,非常感謝!

+0

我想你需要一個通用的方法,這樣可以明確的預期收益類型,喜歡這裏:HTTP:/ /stackoverflow.com/questions/590405/generic-method-in-java-without-generic-argument – mellamokb 2012-07-30 22:00:04

回答

2

如果沒記錯,你需要做的方法本身通用的,就像這樣:

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

是的,但有一個限制據我記憶,將不會包含T類型的對象列表,而不是動物列表?例如,它們最終是動物,但是名單不能同時擁有貓和狗。 – Gamb 2012-07-30 22:03:06

+0

正確。那是目標,不是嗎? – cdhowie 2012-07-30 22:05:07

+0

我想他想要返回混合特定類的列表,而不是包含相同類型對象的列表,但我可能是錯的。 – Gamb 2012-07-30 22:09:30