Java generics, it's enough to know this.

Source: Internet
Author: User

This article directory:

    1. What is a Java generic?
    2. Examples of common generic types
    3. Type Erase
    4. Why Java generics are used
    5. Learn pecs principles with examples

What is a Java generic?

    • Official definition
Generics are a new feature of Java SE 1.5, and the nature of generics is a parameterized type, meaning that the data type being manipulated is specified as a parameter.
This type of parameter can be used in the creation of classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively.
    • Popular explanations
placeholder , that is, if the placeholder is T, then the data type for this declared structure operation is type T.

Ii. General example of generic notation

    • Type T, for generic classes or generic methods

Generic class definition:

 Public class Apiresult<t> {

int ResultCode; String resultmsg; T resultobject;    The construction method and the Get,set method are omitted. }

To define a generic method:

  

 Public class Jsonutil {        public <T> t  Str2json (String jsontext,class target) {        T result =null;         //         return  result;}    }

Use:

Generic classes use
apiresult<user> result=New apiresult<user>(); Result.setresultcode (0); Result.setresultmsg ("Success"); Result.setresultobject (new User ());

Apiresult<list<user>> result2=new apiresult<list<user>> ();
Result.setresultcode (0);
Result.setresultmsg ("Success");
Result.setresultobject (userlist);

Apiresult<integer> result3=new apiresult<integer> ();
Result3.setresultcode (0);
Result3.setresultmsg ("Success");
Result3.setresultobject (99);

Generic methods use

String userjsontext= ".... Omit ", dogjsontext=" .... Omit ";;
User U=jsonutil.str2json (Jsontext,user.class);
User U=jsonutil.str2json (Jsontext,dog.class);

    • K,v type, similar to the map interface.

Defined:

 Public class Resultmap<k,v> {    private  K key;     Private V value;       Omit set, Get  method


Public void put (K key,v value) { this. key=key; this. value=value; }}

Use:

        resultmap<string,user> resultmap=New resultmap<>();        Resultmap.put (new User ());
    • ? Extends type
extends T> represents the upper bound of the type, which indicates that the parameterized type may be a subclass of T or T
    • ? Supper Type
<? Super t> represents the lower bound of the type (called the superclass in Java core), which indicates that the parameterized type is a supertype of this type (the parent type) until the object

  

Third, type erase

First look at an example, the operate class is as follows:

 public  class   Operate { static  void   main (string[] args) {list
    <string> names=new  arraylist<string>         ();        Names.add ( "Jack" );        Names.add ( "Tom" );        Names.add ( "Peter" );  for   (String name:names) {SYSTEM.OUT.PR        Intln ( "Wellcome:" +name); }    }}

After the corresponding class file is deserialized , we use Java-gui to decompile the. exe to see the compiled code as follows

Found no, there is no <String> this part. This limit is "erased" for generic type string. When writing code, generics do check, type does not correspond, cannot add, but the generic type is removed after compilation.

Iv. What to use Java generics

After the "type erase" is described in the third section above, it is better to say why Java generics are used. The generics here is the equivalent of "Yexiaoyu", first set the "Rules", I list<string> this is to operate

String type, you cannot insert the person object. It's just for type safety. So the benefits are:

type safety : By knowing the type limits of variables defined with generics , the compiler can validate the type hypothesis at a much higher level. Without generics , these assumptions exist only in the programmer's mind (or, if you're lucky, in code comments).

To eliminate forced type conversions:

// The code does not use generics: New ArrayList (); Li.put (new Integer (3= (Integer) li.get (0); // The code uses generics: New Arraylist<integer>(); Li.put (new Integer (3= li.get (0);

Understanding the above so much, is enough for daily use generics. Below to understand the pecs principle

V. Principles of PECS

First look at the example:

  Here you define three classes, Spiring,summer inherit season 
Public class Season { // Spring extends Season { Span style= "color: #008000;" >// Summer extends Season { Span style= "color: #008000;" >// }
        extends season> list1=New arraylist<>();         // List1.add (New Spring ()); // the compilation does not pass here because the compiler cannot determine the type that the list holds. 
        list<? Extends season> list2=new arraylist<spring>();//        List2.add (New Spring ());//also cannot compile
//Through the above, we know? Extends season indicates that the type that can be received is seaon or its subclasses.
But not here, because it's possible to pass in spring, or summer, and the compiler can't determine exactly what it's coming in,
So it is not safe to add objects to it, but it can receive assignments of subclass types. As follows:
//List<spring> list3=NewArraylist<spring>(); List<?extendsSeason> List4=list3;//In contrast to the above list2, it is not possible to add the spring type Object directly//However, you can assign a list of spring types directly to a value. List<Season> seasons=NewArraylist<season>(); List<?SuperSpring> spring=seasons; Spring.add (NewSpring ());//OK//Spring.add (New Summer ());//Error//Spring.add (New Season ());//Error//Spring.add (New Object ());//Error

list<?SuperSeason> sea=NewArraylist<>(); Sea.add (NewSpring ());//OKSea.add (NewSummer ());//OKSea.add (NewSeason ());//OK//Sea.add (New Object ());//ErrorList<?SuperSpring> spring=NewArraylist<>(); Spring.add (NewSpring ());//OK//Spring.add (New Summer ());//Error//Spring.add (New Season ());//Error//Spring.add (New Object ());//Error

Here, the pecs principle is as follows:

If you want to read data of type T from the collection and cannot write to the extends  wildcard character, (Producer extends) if you want to write data of type T from the collection and do not need to read  Super wildcard character (Consumer Super) do not use any wildcard characters if both are saved and taken. 

Java generics, it's enough to know this.

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.