gpt4 book ai didi

java - 将子类型集合分配给父类型

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

以下代码不会给出任何错误:

List<A> l = new LinkedList<A>();
l.add(new B()); // B extends A

那么为什么下面会出现错误:

List<B> l = new LinkedList<B>();
List<A> l1 = l;

最佳答案

B延伸A并不意味着List<B>延伸List<A> 。将子类型集合分配给父类型将使其不类型安全。

List<B> ListB = new LinkedList<B>();
List<A> ListA = ListB ; // Suppose you can compile it without error
ListA.add(new C()); // You can put C into ListA if C extends A
B b = ListB.get(0); // Then when you retrieve from ListB, you get a C, not type safe!

您需要一个通配符来保证类型安全并使其编译:

List<B> ListB = new LinkedList<B>();
List<? extends A> ListSubA = ListB ;
ListSubA.add(new C()); // Compile error, a wildcard can prevent user putting C into it
ListB.add(new B()); // You can only add new element by ListB
B b = ListB.get(0); // Type safe

关于java - 将子类型集合分配给父类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50254657/

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