繁体   English   中英

为什么我不能将具有其他类型的实例分配给参数化变量?

[英]Why can't I assign an instance with another type to a parameterized variable?

为什么我不能这样做:

LinkedList<Fruit> myFruits = new LinkedList<Apple>();

错误信息:

Type mismatch: cannot convert from LinkedList<Apple> to LinkedList<Fruit>

以下区别在哪里?

Fruit fruit = new Apple();

考虑使用LinkedList<Fruit>可以做什么 - 并考虑一下您希望此代码执行的操作:

LinkedList<Apple> apples = new LinkedList<Apple>();
LinkedList<Fruit> fruits = apples;
fruits.add(new Banana());

Apple apple = apples.getFirst(); // Safe at compile time, but it's a Banana!

转换是唯一一个在编译时失败的地方。 现在你可以写的是:

LinkedList<? extends Fruit> myFruits = new LinkedList<Apple>();

...然后编译器不会让你向列表添加任何东西,因为它不知道真正的元素类型是什么。 同样你也可以写:

LinkedList<? super Apple> apples = new LinkedList<Fruit>();

现在你可以苹果添加到列表中,但是你不能将苹果列表中取出 ,因为你不知道它的类型是什么。

多态性根本不适用于generic types

LinkedList<Fruit>LinkedList<Apple>即使FruitApple的超级类

请参阅此答案以了解原因。

因为那时你可以添加一个OrangemyFruits ,这不应该工作,因为实际列表是一个Apple列表

例如(如果你能做到这一点);

List<Apple> myApples = new LinkedList<Apple>();
List<Fruit> myFruits = new LinkedList<Apple>();
myFruits.add(new Orange());

现在myApples得到了一个Orange

允许简单的分配,因为复制了引用并保持原始不变。

Apple apple = new Apple();
Fruit fruit = apple;
fruit = new Banana(); // apple is not touched and is still an Apple

而(AtomicReference是一个简单的集合)

AtomicReference<Apple> apple = new AtomicReference<>(new Apple());
AtomicReference<Fruit> fruit = (AtomicReference) apple; // warning but compiles.
fruit.set(new Banana()); // this alters apple as well, making it invalid!
Apple apple2 = apple.get(); // throws ClassCastException.

暂无
暂无

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

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