I am a new java learner. Recently I was reading Generic programming and got my self confused with this...
A<T extends B> and A<? extends B>
extends Number> represents a list of Number or its sub-types such as Integer and Double. Lower Bounded Wildcards: List<? super Integer> represents a list of Integer or its super-types Number and Object.
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.
super is a lower bound, and extends is an upper bound.
allows you to have a list of Unknown types, where as T requires a definite type. best answer +1 from me!
First of all, those are completely different constructs used in different contexts.
A<T extends B>
is a part of generic type declaration such as
public class A<T extends B> { ... }
It declares generic type A
with type parameter T
, and introduces a bound on T
, so that T
must be a subtype of B
.
A<? extends B>
is a parameterized type with wildcard, it can be used in variable and method declarations, etc, as a normal type:
A<? extends B> a = ...;
public void foo(A<? extends B> a) { ... }
Variable declaration such as A<? extends B> a
means that type of a
is A
parameterized with some subtype of B
.
For example, given this declaration
List<? extends Number> l;
you can:
Assign a List
of some subtype of Number
to l
:
l = new ArrayList<Integer>();
Get an object of type Number
from that list:
Number n = l.get(0);
However, you can't put anything into list l
since you don't know actual type parameter of the list:
Double d = ...;
l.add(d); // Won't compile
?
is what is called a wildcard. It means anything that extends B.
When you write List<T extends String>
, your List
can contains only elements of type T
.
When you write List<? extends String>
, your List
can contains any element that extends String
I hope I'm clear, since these concepts are complicated.
If 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