简体   繁体   中英

What is the Use of < ? extends E >

While working with generics I encountered with declaration < ? extends E> < ? extends E> . If I take example of collection interface's addAll method.

Its declaration is like :

   interface Collection<E> {
      public boolean addAll(Collection<? extends E> c);
  }

so from the above declaration of addAll what I have understood (as read from different sources) that

  • ? extends E ? 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

Let's go with this example :

List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);

List<? extends Number> nums = ints; // now this line works
/*
 *without using ? syntax above line did not use to compile earlier 
 */
List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.0);
nums.addall(doubleList); // compile time error 

Error:

The method addall(List< Double >) is undefined for the type List< capture#1-of ? extends Number >

I also read in O'Reilly's 'Java Generics and Collections'

In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure.

So my question is when we can't modify the thing with this, then what is the use? Just to get the elements from that collection if it is a subtype?

So my question is when we can't modify the thing with this , then what is the use ? Just to get the elements from that collection if it is a subtype ?

Yes, that is correct. Just to get the elements from it.

Keep in mind that Collection<? extends Number> Collection<? extends Number> is the type of the variable , not the type of the collection itself. The meaning of the wildcard syntax is more akin to a pattern that a specific collection must match, than a type in the sense "object X is of type T".

If Java did not have wildcards, you would be very constrained in what you can express. For example, the generic addAll method would accept only a collection of the exact same component type.

This means that addAll method allow any collection of object that extends the E class. For example, if G extends E, you can add an array of G to this collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM