Java – generics and inheritance?

See English answers > java: can't to generic list mylist 4

public static void main(String... args) {
    List<Child> list1 = new ArrayList<Child>();
    method2(list1);
}

public static void method2(List<Parent> list1) {
}

I got the following compilation errors

The above problems can be solved by modifying list < parent > LIST1 to list 1

But if I try to add the following sub objects

public static void method2(List<? extends Parent> list1) {
    Child child1 = new Child();
    list1.add(child1);
}

It has a compilation error again

So my question is, if list < child > can be passed as a parameter to list LIST1 in list ?

Solution

This is a very common misunderstanding The fact that child extends parent does not make list < child > extend list < parent > In a situation like this, it sounds very intuitive, but it does From the Java Tutorial:

Read this for details

As for adding to the list, the short answer is: imagine that you have another class child2 extended parent. Now, the list you receive in method2 (list LIST1) can be list < Child1 & gt; Or list < child2 > Therefore, since the second case is possible, adding Child1 objects is not type safe

Now, the fact that you can't add doesn't mean you can't do other useful things, such as getting size

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>