Contravariance and covariance in Java

Source: Internet
Author: User

//Public Final Class Integer extends numberNumber num =NewInteger (1); List<Number> list =NewArraylist<>(); List.add (NewInteger (3)); ArrayList<Number> list =NewArraylist<integer> ();//Type mismatchList<?extendsnumber> list =NewArraylist<number>(); List.add (NewInteger (1));//Error

Why can an object of number be instantiated by an Integer, while an object of arraylist<number> cannot be instantiated by arraylist<integer>?

The < in list;? Extends number> declares that its element is a derived class of number or number, why can't I add an Integer?

To solve these problems, you need to understand the inversion and covariance in Java and the use of wildcard characters in generics.

1. Contravariance and covariance

The string type in Ava is inherited from object, let's make string≦object, which means that string is the subtype of object and the object of string can be assigned to object. and the array type of object object[], understood to be a new type constructed by object, can be considered a type of construction, F (Object), then you can describe covariance and contravariance:
When A≦b, if there is f (a) ≦f (B), then f is called covariant;
When A≦b, if there is f (B) ≦f (a), then f is called inversion;
If neither of the above relationships is true, it is called immutable.

2. Wildcard characters in generics for inversion and covariance

Generics in Java are immutable, and sometimes you need to implement contravariance and covariance. Then you need a wildcard character?.
<? Extends> implements the covariance of generics, such as:

 

extends New Arraylist<> ();  

“? Extends number "is the wildcard character"? " The upper bound is number, in other words,

“? Extends number "can represent number or its subclasses, but not the parent class of number (such as Object), because the upper bound of the wildcard is number.
So there's "? Extends number "≦number, then list<? Extends number>≦list< number >. Then there are:
  

extends New Arraylist<integer>();  Listextendsnew arraylist<float> ();  

However, you cannot add any object other than null to LIST001, list002. It can be understood that,list<integer> can add interger and its subclasses,list<float> can add Float and its subclasses,list<integer>, list<float > are list< Extends Animal> subtype, if the subclass of float can be added to list< In extends animal>, it is clear that the subclass of float can also be added to the list<integer>, which is obviously not possible. Therefore Java in order to protect its type consistent, prohibit to list< Extends number> add any object, but you can add null.

<? The super> implements the inverse of generics, such as:

Super New Arraylist<> ();  

“? Super number "is a wildcard"? " The lower bound is number. In order to protect the consistency of the type, because "? Super number "can be a parent of object or other number, because it cannot be determined by its type, it cannot go to list< Super Number > Add any parent class object of number. But can be to list<? Super Number > Add number and its subclasses.

Super New Arraylist<number>();  ListSupernew arraylist<object>();  List001.add (new Integer (3));  List002.add (new Integer (3));  

Pecs Principles
Producers (Product) use extends, and consumers (Consumer) use super.
Producers use extends
If you need a list to provide elements of type T (that is, you want to read the elements of type T from the list), you need to declare this list as < Extends T>

However, you cannot add any elements to the list.
Consumers use Super
If you need a list to use elements of type T (that is, you want to add elements of type T to the list), you need to declare this list as <. Super t>

such as List<? Super Integer>, there is no guarantee of the type of element to read from.
That is, producers and consumers.
If a list is to be produced and consumed, you cannot use the generic wildcard declaration list

Java.util.Collections's Copy method (JDK1.7) perfectly interprets the PESC

 Public Static<T>voidCopy (LIST&LT;?SuperT> dest, list<?extendsT>src) {      intSrcsize =src.size (); if(Srcsize >dest.size ())Throw NewIndexoutofboundsexception ("Source does not fit in dest"); if(Srcsize < Copy_threshold | |(srcinstanceofRandomaccess && destinstanceofrandomaccess)) {           for(inti=0; i<srcsize; i++) Dest.set (i, Src.get (i)); } Else{listiterator<?SuperT> di=Dest.listiterator (); Listiterator<?extendsT> si=Src.listiterator ();  for(inti=0; i<srcsize; i++) {di.next ();          Di.set (Si.next ()); }      }  }  

Ref: 52245475

Contravariance and covariance in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.