Upper and lower bound wildcards in java generics

In java generics, the wildcard ? represents an unknown type, which is equivalent to <? extends Object>, <? extends T> is an upper bound-qualified wildcard, <? super T> is a lower bound-qualified wildcard.

1. Difference

In a list, the object types that can be stored and read by the upper and lower bound wildcards are shown in the following figure:

 

 

2. Principles

The use of upper and lower bound wildcards should follow the PECS principle: Producer Extends, Consumer Super.

Qualified wildcards always include themselves

Upper bound type wildcard: add method is restricted

Nether type wildcard: get method restricted

If you want to get data from a data type, use the ? extends wildcard

If you want to write the object into a data structure, use the ? super wildcard

If you want to save and get it, don't use wildcards

Generic wildcard upper and lower bounds cannot be declared at the same time

 

refer to:

How to understand super in Java generics <? super T>? How is it different from extends? - Fat Answer- Knowing https://www.zhihu.com/question/20400700/answer/117464182

https://blog.csdn.net/claram/article/details/51943742

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325214024&siteId=291194637