<? extend T> and <? super T> use

<? extend T> 和 <? super T>

<? extend T> Indicates the upper limit of wildcards, and the generic types created are all T or subclasses of T.

如 class A extend Father,class B extend Father。

List<? extend Father> list = new ArrayList<Father/A/B>(); However, it is not sure which type of Father it is, and it is not sure whether there is a relationship between A and B. So there is no way to use the list.add() method (except null). Just like List<String> and List<Integer> cannot define generics, list can add("1") and add(123); but you can use the get() method, because they are all subclasses of Father . The type of get must be Father.

<? super T> identifies the lower limit of the wildcard, and the generic types created are all the parent class of T or T.

如 class A extend Father,class B extend A,class C extend B。

List<? super A> list = new ArrayList<Father/A>(); Because the lower limit is defined. So list can add A or a subclass of A, such as list.add(new A()), list.add(new B()), list.add(new C()). When using get, you must strengthen the transfer, otherwise you can only use the Object class to connect.


PECS principles

PECS(Producer Extends Consumer Super)原则。

Literally means that the producer is to be inherited as the upper bound E of the upper bound wildcard <? extends E>, and the consumer inherits other classes to be regarded as the lower bound E of the lower bound wildcard <? super E>. It should be that when the type being passed in requires a lot of get operations to obtain data, then please use the upper bound wildcard. At this time, the upper bound is like a producer, because it can be continuously obtained, and when it is necessary to continuously add If you add data by method, please use the lower bound wildcard. At this time, the lower bound is like a consumer, because it keeps asking for it, because we are constantly adding elements to it.

Guess you like

Origin blog.csdn.net/yytree123/article/details/129089021