gpt4 book ai didi

java 泛型扩展和列表

转载 作者:行者123 更新时间:2023-12-02 07:40:00 26 4
gpt4 key购买 nike

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

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 泛型扩展和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11730277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com