How to understand the wildcard type parameters / covariance / inverter sex?

The Java Collection interface, the method signature addAll method Why not  void addAll (Collection <E> items)  , but  void addAll (Collection <? The extends E> items)  it?

This is because generics in Java is not the type of change , such as:  List <String>  and not  List <Object>  subtype.

If addAll method signature  void addAll (Collection <E> items)  , then the following code will compile error:

void combine(Collection<Object> to, Collection<String> from){
    to.addAll(from); // 编译错误
}

Since  void the addAll (Collection <E> items)  method takes type Collection <Object> parameter, the Collection <String> not Collection <Object> subtype.

In fact, the above code is very simple, just add an element of type String as a collection of all the elements to another set of elements of type Object, this is not a problem element type conversion.

The use  void addAll (<? Collection the extends E> items)  method signature, then it means addAll accepts a set of E or its sub-type of the object as a parameter, namely: type Collection <Object> is to object whose addAll method takes type or as a set of objects object object subclass as a parameter. As we all know, String type is a subtype of Object class, so Collection <String> naturally meet the requirements.

 

Wildcard type parameters

 Collection <? The extends E>   in ? Is the wildcard type parameters.

  <? Extends E> Collection  of such an approach means that we can secure from which to read E instance, because the type of each element in the collection is E or sub-type E; at the same time, we can not assure write elements in a collection, because we can not determine the type of wildcard ? In the end is E or which sub-type E.

This band extends Limited ( upper bound wildcard type) of such type is covariant (covariant) .

And disguised corresponding Association is denatured (contravariance) ,   Collection <? Super String>   wording means that we can safely put the String object to the collection.

such as:

void combine(Collection<? super String> to, Collection<String> from)

Since the collection to the type of elements in the String superclass, so we can put the safety of the String object to the collection to the.

 

Guess you like

Origin www.cnblogs.com/flying-rookie/p/11127303.html