What is the difference between this method declaration:
public static <E extends Number> List<E> process(List<E> nums){
and
public static List<Number> process(List<Number> nums){
Where would you use the former?
super is a lower bound, and extends is an upper bound.
The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
extends E> means any object including E that is child of E .
allows you to have a list of Unknown types, where as T requires a definite type. best answer +1 from me!
The first allows process
of a List<Integer>
, a List<Double>
, etc. The second doesn't.
Generics in Java are invariant. They're not covariant like arrays.
That is, in Java, Double[]
is a subtype of Number[]
, but a List<Double>
is NOT a subtype of List<Number>
. A List<Double>
, however, is a List<? extends Number>
.
There are good reasons for generics being invariant, but that's also why the extends
and super
type are often necessary for subtyping flexibility.
super
and extends
for bounded wildcardsextends
Consumer super
" principleIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With