0

我正在尝试在实用程序上正确获取方法签名,以便摆脱一些未经检查的类型转换。到目前为止,我有:

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() 方法的签名进行各种更改,但似乎无法使语法正确,因此我可以传入特定类型的动物并让它返回相同的动物而不会出现类型安全问题。

任何帮助是极大的赞赏!

4

1 回答 1

2

如果有记忆,您需要使方法本身通用,如下所示:

public <T extends Animal> static Tuple<List<T>, Long> getAnimalsWithTotalWeightUnder100(List<T> beans) {
于 2012-07-30T21:59:19.527 回答