我试图让一个实用程序的方法签名正确,以便我可以摆脱一些未检查类型铸造。到目前为止,我有: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