Is there a difference between these two List
s?
List<Something> a;
List<? extends Something> b;
I know that for example
List<Object> a;
List<?> b;
List c;
and
List<Something> a;
List<? extends SomeInterfaceSomethingImplements> b;
are all different, but how about these? And is it different if Something
was replaced with Object
?
List<Object> a;
List<? extends Object> b;
List<Something>
is a list of objects of type Something
.
List<? extends Something>
is a list of objects of some particular type which extends Something
.
So, List<Object>
can have objects of any class that extends Object
.
But List<? extends Object>
can only be initialised to or assigned as a List of a objects of a particular class that extends Object
When is this useful? Say you want to write a method that takes a List
of Objects
and prints each item:
void print(List<Object> list) {
for (Object obj: list) {
System.out.println(obj)
}
}
Now, let's say you have a List<Integer>
. You cannot pass it to the above method, because print
takes List<Object>
, and List<Integer>
cannot be assigned to a List<Object>
. To get around this, we redefine print
as:
void print2(List<? extends Object> list) {
for (Object obj: list) {
System.out.println(obj)
}
}
Now, we can pass List of any subclass of Object to print2
. print2
will accept List<Integer>
, List<String>
etc.
On the flip side, you cannot add anything to the list inside print2
, because print2
does not know the concrete subtype of Object
which is used. Hence you can use ? extends ...
only in methods where you do not have to add anything to the List
.
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