我正在尝试在实用程序上使方法签名正确,以便我可以摆脱一些未经检查的类型转换。到目前为止,我有:
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 :(得分:2)
如果内存服务,你需要使方法本身通用,如下所示:
public <T extends Animal> static Tuple<List<T>, Long> getAnimalsWithTotalWeightUnder100(List<T> beans) {