[java] Difference between <? super T> and <? extends T> in Java

The up voted answers covers the details on many aspects. However, I would try to answer this in different way.

There are 2 things we need to consider,

1. Assignment to the list variable

List<? extends X> listvar;

Here, any list of X or list of subclasses of X can be assigned to listvar.

List<? extends Number> listvar; listvar = new ArrayList<Number>(); listvar = new ArrayList<Integer>();


List<? super X> listvar;

Here, any list of X or list of superclasses of X can be assigned to listvar.

List<? super Number> listvar; listvar = new ArrayList<Number>(); listvar = new ArrayList<Object>();

2. Perform Read or Write operation on the list variable

`List<? extends X> listvar;`

You can use this feature to accept a list in method arguments and perform any operations on type X (Note: You can only read objects of type X from the list).

`List<? super Number> listvar;

You can use this feature to accept a list in method arguments and perform any operations on type Object as You can only read objects of type Object from the list. But yes, additional thing here is , you can add objects of type X into the list.

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to generics

Instantiating a generic type Are these methods thread safe? The given key was not present in the dictionary. Which key? Using Java generics for JPA findAll() query with WHERE clause Using Spring RestTemplate in generic method with generic parameter How to create a generic array? Create a List of primitive int? How to have Java method return generic list of any type? Create a new object from type parameter in generic class What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?