简体   繁体   English

Java Generics - 通过 inheritance 层的上限

[英]Java Generics - Upper Bounds through layers of inheritance

With a single layer of inheritance I can do something like this:使用单层 inheritance 我可以这样做:

// Dog extends Animal
List<Dog> dogs = ...;

// Cat extends Animal
List<Cat> cats = ...;

List<? extends Animal> animals = new ArrayList<>();
animals.addAll(cats);
animals.addAll(dogs);

I can do this without casting, which is nice.我可以在没有铸造的情况下做到这一点,这很好。

But what if I have a scenario like the following?但是,如果我遇到如下情况怎么办?


// Plant extends LivingBeing
List<Plant> plants = ...;

// Animal extends LivingBeing
// Cat extends Animal
List<Cat> cats = ...;

List<? extends LivingBeing> livingThings = new ArrayList<>();
// This is fine
lvingThings.addAll(plants);

// FIXME: Fails because Cat doesn't directly extend LivingBeing
livingThings.addAll(cats);

Is there a way to specify an upper bound that is not a direct parent of all members of the list, so that I can avoid casting?有没有办法指定一个上限,该上限不是列表所有成员的直接父级,这样我就可以避免强制转换?

Your first example doesn't compile.您的第一个示例无法编译。 Both are caused by the ? extends两者都是由? extends ? extends part. ? extends部分。 The issue is that as soon as the initialization is done, the compiler already forgot the actual type.问题是一旦初始化完成,编译器就已经忘记了实际类型。 That means that after initializing livingThings , the compiler thinks it can be a List<LivingBeing> , List<Animal> or List<Cat> (all of which would allow adding cats), but also List<Dog> or List`, which don't allow cats.这意味着在初始化livingThings之后,编译器认为它可以是List<LivingBeing>List<Animal>List<Cat> (所有这些都允许添加猫),但也可以是List<Dog> or List`,它们不'允许猫。

If you want a list with things that can be any type of living being, you must declare it as such: List<LivingBeing> .如果你想要一个包含任何类型生物的列表,你必须这样声明它: List<LivingBeing> Otherwise you can't add anything anymore except null .否则除了null之外你不能再添加任何东西。

The latter is true for any Collection<? extends T>后者对任何Collection<? extends T> Collection<? extends T> for any type T . Collection<? extends T>为任何类型T The only value that is safe for any type that matches ? extends T对于匹配的任何类型都是安全的唯一值? extends T ? extends T is null . ? extends Tnull

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM