为什么我不能做到这一点:为什么我不能将具有另一种类型的实例赋值给参数化变量?
LinkedList<Fruit> myFruits = new LinkedList<Apple>();
错误消息:
Type mismatch: cannot convert from LinkedList<Apple> to LinkedList<Fruit>
哪里是区别以下?
Fruit fruit = new Apple();
为什么我不能做到这一点:为什么我不能将具有另一种类型的实例赋值给参数化变量?
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>();
...然后编译器不会让你任何添加到列表中,因为它不知道真正的元素类型是什么。同样,你coudl写:
LinkedList<? super Apple> apples = new LinkedList<Fruit>();
现在你可以添加苹果到列表中,但你不能让苹果淘汰之列,如再你不知道类型是什么。
感谢您的回答。我刚刚找到http://stackoverflow.com/a/6828257/562769这也有帮助。 –
,因为这样你可以一个Orange
添加到myFruits
而不应作为实际列表工作是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.
的[是\`名单
可能重复?为什么不是Java的泛型隐式多态?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicit) – jlordo