Problems encountered in Java Learning (ii) generics in <? Extends t> and <? The difference between Super t>

Source: Internet
Author: User

For one is list<? Extends a reference to a t> type List1, which is actually a specific type that is not specified by a list1 reference, it is a seed class of T, but what kind of subclass is the compiler cannot determine, and therefore cannot be used to add objects, However, because you can be sure that any object in this list1 is at least type T, you can use Get () to return an object of type T.

And for one is list< The Super t> type references List2, which is actually a base class of T, but because it is not possible to determine which base class it is, the List2 uses get () to return only an object type, the original T type is lost, but because the parameter is already known to be a base class of T, So it is safe to add a subtype of T or T to it, but if you add any base class to it, you will get an error due to uncertainty (even if you add the object type).

1 ImportJava.util.*;2 3  Public classDemo_twentyeight {4     Static classGeneric1<t>{5         PrivateT Item;6          Public voidput (T item) {7              This. item=item;8         }9     }Ten  One     Static classGeneric2<t>{ A T Item; - T Get () { -             returnitem; the         } -     } -     Static<T>voidF1 (generic1<?SuperT>generic1,t Item) { - generic1.put (item); +     } -     Static<T>voidF2 (generic2<?extendsT>Generic2) { + generic2.get (); A     } at      Public Static voidMain (string[] args) { -Generic1<fruit> g1=NewGeneric1<fruit>(); -G1.put (NewApple ()); -G1.put (NewFruit ()); - //G1.put (New Object ()); //compilation does not pass -Generic2<fruit> g2=NewGeneric2<fruit>(); inFruit f1=g2.get (); -     } to  +}

A more detailed answer (written by a great God): http://zhidao.baidu.com/question/646868566975781205.html

Problems encountered in Java Learning (ii) generics in <? Extends t> and <? The difference between Super t>

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.