Java泛型扩展和列表

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

任何帮助是极大的赞赏!

最佳答案

如果有内存,则需要使方法本身通用,如下所示:

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

关于java - Java泛型扩展和列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11730277/

10-09 00:24