Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between List<Something> and List<? extends Something>? [duplicate]

Tags:

java

generics

Is there a difference between these two Lists?

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;
like image 997
PurkkaKoodari Avatar asked Dec 12 '22 11:12

PurkkaKoodari


1 Answers

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.

like image 135
Hari Menon Avatar answered May 10 '23 12:05

Hari Menon