2012-07-30 74 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