Covariance of Java generics

Source: Internet
Author: User

In the previous article, "Basic use of Java generics," the following question was left, and a subtype could be added to a generic of the parent type. The ability to implement such a function must be aided by covariance.

Experiment Preparation

Now, on the basis of the decorator type shown in the previous article, add some code, as seen in Listing 1.

Code Listing 1

   /**     *      Description: EXP2 use br/>     * Author:jiaan.gja<br/>     * History: (version number) author time gaze <br/>     * @param itemli St     *    /public void DoDecorate2 (list<? extends t> itemList) {for        (int i = 0; i < itemlist.size (); i++) {            System.out.println (Itemlist.get (i));        }    }        /**     *      Description: EXP2 use <br/>     * Author:jiaan.gja<br/>     * History: (version number) author time gaze <br/>     * @par Am itemList     * @param t     *    /public void AddDecorate2 (list<? extends t> itemList, T t) {//ItemList. Add (t);    }

You can see that this is almost the same as the Dodecorate and Adddecorate methods in the basic use of Java generics, the only difference is to change the list<t> to List< Extends T>, such a syntax is called covariant. Suppose you have written the above code in the IDE. It must be found that the statement Itemlist.add (t) in AddDecorate2 has been compiled with an error. So we will first itemlist.add (t); This statement is temporarily staring out. Let's see if DoDecorate2 has reached our expectations.

Experiment: Generic covariance

Now we are trying to use the covariant. That is, call the DoDecorate2 method, as seen in code Listing 2.

Code Listing 2

/** * Class Name: exp2<br/> * Description: Generic covariant use <br/> * Author: jiaan.gja<br/> * created: August 20, 2015 <br/> * * History:  (version number) author time gaze */class Exp2 {public static void main (string[] args) {decorator<auction> Decoratora = new        Decorator<auction> ();        list<auction> ListA = new arraylist<auction> ();        Auction Auctionone = new Auction ("Auctionone");        Auction auctiontwo = new Auction ("Auctiontwo");        Decoratora.adddecorate2 (ListA, Auctionone);        Decoratora.adddecorate2 (ListA, auctiontwo);                Decoratora.dodecorate2 (ListA);        decorator<table> Decoratorb = new decorator<table> ();        list<table> Listb = new arraylist<table> ();        Table Tableone = new Table ("Tableone", 10);        Table Tabletwo = new Table ("Tabletwo", 20);        Decoratorb.adddecorate2 (Listb, Tableone);        Decoratorb.adddecorate2 (Listb, tabletwo);                Decoratorb.dodecorate2 (LISTB); decorator<service> Decoratorc = new decorator<service> ();        list<service> LISTC = new arraylist<service> ();        Service ServiceOne = new Service ("ServiceOne", "MethodOne");        Service servicetwo = new Service ("Servicetwo", "methodtwo");        Decoratorc.adddecorate2 (LISTC, ServiceOne);        Decoratorc.adddecorate2 (LISTC, servicetwo);                Decoratorc.dodecorate2 (LISTC);        /* Covariance Test start */Decoratora.dodecorate2 (LISTB);            Decoratora.dodecorate2 (LISTC); }}
First of all. We see that the DoDecorate2 method is at least as effective as the Dodecorate method in basic use of Java generics.

Because the type that declares the Decoratora is Decorator<auction>, then the doDecorate2 of the instance Decoratora can feel the following:

extends Auction> itemList
And the type of LISTB is the type of ARRAYLIST&LT;TABLE&GT;,LISTC is Arraylist<service&gt, that is to say covariant agrees:
extends New Arraylist<auction>(); Listextendsnew arraylist<table>(); Listextendsnew arraylist<service> ();
This indicates that the itemlist is capable of storing auction. can also store table and service.

Let's do this. If, when you want to get the table from Itemlist, the Java compiler suspects that this might actually be a service. Therefore, there will be compile errors. There is no problem if you want to get auction from itemlist, because both table and service can be actively converted to the parent class auction. These guesses can be verified by code Listing 3.

Code Listing 3

        list<?

Extends auction> itemList = ListA; Auction a = itemlist.get (0); Table t = itemlist.get (0); Service s = itemlist.get (0); ItemList = Listb; A = Itemlist.get (0); t = itemlist.get (0); s = itemlist.get (0); ItemList = LISTC; A = Itemlist.get (0); t = itemlist.get (0); s = itemlist.get (0);

Similarly, when you want to add a table to itemlist, the compiler suspects that Itemlist is actually a arraylist<service> There is no problem when acquiring auction, so will joining auction be able? Because itemlist may be arraylist<service> or ARRAYLIST&LT;TABLE&GT, this is not actually possible, based on the conclusions of the previous Java generics basic use. Can be verified with the following code:
        Auction auctionthree = new Auction ("Auctionthree");        Itemlist.add (auctionthree);        Auction tablethree = new Auction ("Tablethree");        Itemlist.add (tablethree);        Auction servicethree = new Auction ("Servicethree");        Itemlist.add (Servicethree);

So this also illustrates the statement Itemlist.add (t) in the addDecorate2 that you just started to see, and why the error was compiled. However, we still want to be able to add subtypes to the generic of the parent type declaration. What's the deal? Java, of course, also takes this into account. Take a look at the next "Java generics inversion".

Summarize

If you get subclasses from generics, you should use covariance.

Covariance of Java generics

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.