JAVA generic? Extends and? Super comparison

Source: Internet
Author: User

The generic type can be used after JDK.
A. generic class declaration, such as public class GeneralT <A>
B. generic interface declaration, such as public interface GenIntf <A>
C. Generic method declaration, as shown in figure
Public <T extends BaseCls> void thisIsT (List <T> list, T e ){
List. add (e );
}
D. constructor declaration, such as GeneralT <BaseCls> pgt = new GeneralT <BaseCls> ();

What is the main introduction here? Extends and? Super.
1 ,? Extends is called an up shape.
ArrayList <? Extends BaseCls> list1 = new ArrayList <BaseCls> ();
This means that all the list1 objects are sub-classes of BaseClse, so that you can use list. get (index)
The resulting classes are all subclasses of BaseCls or BaseCls.
BaseCls cls = list1.get (0); // valid
List1.add (new BaseCls (); or list1.add (new CldCls (); are invalid.
The add function cannot be used to store objects. What is the purpose of this function.
Generally, it is defined? Extends BaseCls parameters can only be used to retrieve data from them.
Which of the following downbound methods is acceptable? List of extends BaseCls types
Public void downbound (List <? Extends BaseCls> list ){
For (BaseCls cls: list ){
Cls. func ();
}
}
ArrayList <BaseCls> list1 = new ArrayList <BaseCls> ();
ArrayList <CldCls> list2 = new ArrayList <CldCls> ();
Downbound (list1); and downbound (list2); are valid.

2 ,? Super BaseCls is called a downward shape.
ArrayList <? Super BaseCls> list2 = new ArrayList <BaseCls> ();
This means that the list2 can only contain BaseClse or its subclass.
List2.add (new BaseCls (); or list2.add (new CldCls (); are valid.
List2.get (index) returns the Object type because it is not known to be the specific class.
The type of the object to be put in is restricted. Why is it not BaseCls? I don't understand it here...
Public void upperbound (List <? Super BaseCls> list ){
List. add (new BaseCls ()
List. add (new CldCls ());
}

 


Author: kkdelta

Related Article

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.