Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is <? extends ...> exclusivity of method parameters?

Tags:

java

Let's say I have two classes A and B which extends A. With the following method I can print a Collection of A or something extending A:

private static void print(Collection<? extends A> collection) {

    for (A element : collection) {
        System.out.println(element);
    }

}

It's great, I can do something like:

public static void main(String[] args) {

    List<A> l1 = new ArrayList<>();
    l1.add(new A());
    l1.add(new B());
    print(l1);

    List<B> l2 = new ArrayList<>();
    l2.add(new B());
    l2.add(new B());
    print(l2);

}

Now my question is why in my method main (or somewhere else) I can write this

List<? extends A> l3 = new ArrayList<>();

but not this

l3.add(new A());
l3.add(new B());

I do understand why I can not add an instance of A or B in l3. But why the first statement which seems useless is authorized ?

EDIT

I ask with another words because I think my question is misunderstood.

What can I do with my empty list List<? extends A> l3 = new ArrayList<>(); ? I know it's not possible to add anything because the type of the list is unknown.

like image 316
cheb1k4 Avatar asked Dec 29 '15 15:12

cheb1k4


People also ask

What does <? Extends E mean in Java?

extends E means that it is also OK to add all members of a collection with elements of any type that is a subtype of E.

What is difference between extends and super in generics?

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.

Is extends Object a bounded wildcard?

extends Object> is a bounded wildcard (an unknown that extends Object , whereas <E extends Object> is type bounded ( E requires a Parameterized type that extends Object ).

How do you restrict the types used as type arguments in generic classes and methods?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.


1 Answers

List<? extends A> l3 means that l3 might be a List<A> or it might be a List<B>. <? extends A> means the compiler doesn't know and cannot safely assume any more than that.

Since it might be List<B>, l3.add(new A()) is not safe. The List would be corrupt, since it would not truly contain only instances of B.

like image 96
VGR Avatar answered Nov 02 '22 22:11

VGR