The concept is simple to understand
List<? extends T>
Indicates that all the subclasses of type T exist in the collection, including T itselfList<? super T>
Indicates that all the collections are stored in the parent class of type T, including T itself
Interpretation of code samples
Parent-child class code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
relation chart:
Test code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
About List<? super T>
add aspect
1 |
|
1 |
|
Executing the above line of code is not allowed, because the collection type of listA is Animal or a higher parent class. Think about it, if the represented type is Animal, how can add its parent class Biological? Of course not allowed.
1 2 |
|
Executing the above two sentences can be executed normally, because whether it is Animal or Animal's subclass Dog, it can be stored in the collection of the parent class whose collection type is Animal or higher. A bit of a mouthful, but that's what it means.
1 |
|
Adding Flower is of course not possible, because it is not a subclass of Animal.
return value aspect
1 |
|
Because the collection type of listA is Animal or a higher parent class, it is not clear which class it will be, but we should all know that the parent class of all classes is Object, so the return value is of type Object.
About List<? extendsT>
add aspect
1 |
|
1 |
|
Executing the above code is not allowed, because the collection type of listB is Plant or a subclass of Plant. Think about it, if the represented type is Tree, a subclass of Plant, how can it add its parent class Plant? So it is similar to the above understanding, which is the reverse understanding. It can be clearer by looking at the picture.
1 |
|
In the same way, how to represent the type is the subclass Rose (rose) of Flower, so of course it is not possible to add its parent class Flower.
1 |
|
This is the special case, you can add null, but it doesn't make sense.
return value aspect
1 |
|
Because the collection type of listB is Plant or its subclasses, it is not clear which class it will be, but we can know that the highest type is Plant, so the return value is of Plant type.
Summarize
- List<? extends T> means that all the parent classes of type T are stored in the collection, including T itself
- add: Cannot add any object (special case: null can be added)
- get: The object type returned by get is T
- List<? superT>表示该集合中存在的都是类型T的子类,包括T自己
- add:只能添加T及T的子类
- get:get返回的对象类型为Object
本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注脚本之家的更多内容!