Javase (ix)-Generic (generics)

Source: Internet
Author: User
Tags gety java se

Objective

These days to share how to build a cluster, this one to introduce you are generics, in our many Java source code is a lot of complex generics! What is a generic type?

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 .

The benefits of introducing generics into the Java language are simple and secure. In the case of Java SE 1.5, without generics, by referencing the type object to implement the "arbitrariness"of the parameter, the disadvantage of "arbitrariness" is to do an explicit coercion of type conversion, which is required

The developer is able to predict the actual parameter type. In the case of coercion of type conversion errors, the compiler may not prompt for an error and an exception occurs at run time, which is a security risk.

The benefit of generics is that it checks for type safety at compile time, and all casts are automatic and implicit to increase the rate of reuse of the code. That's not much nonsense, we get to the point:

I. Introduction to generics 1.1, generics overview

Generics are a new feature of JDK 1.5 , the nature of which is the parameterized type (parameterized type), which means that the data type being manipulated is specified as a parameter, specifying a specific type when used .
This type of parameter can be used in the creation of classes, interfaces, and methods, which are referred to as generic classes, generic interfaces, and generic methods, respectively.
A generic type can be passed in in the future only as a reference type and not as a base type .

// compiled by    list<string>    list<action>    list<integer>    list<integer[]>    //  Compile error    list<int>

1.2. Generic Features

Generics in Java only work during editing, and the generic information is erased at run-time .

The role of type safety checks is only initiated during compilation, and the runtime does not work .

For example:list<string> List = new arraylist<string> ();

Although a generic string is specified, it is still possible to store other types of data in the list at run time. (for example, using a reflection method)

Second, generic type

A generic class is a class that has one or more type variables (the type is parameterized) .
It is very simple to define a generic class simply by adding <> to the class name, and then adding the type parameter to it.

Note: Type variables are used in uppercase and relatively short, which is very common. In the JDK, the variable e is used to represent the element type of the collection, and K and V represent the type of the keyword and the value, respectively. (You can also use other letters or one or more letters if needed)

Example 1:

The t here is based on the type that will be passed by the user when using the point class.

 Public classPoint<t> {            PrivateT x; PrivateT y;  PublicT GetX () {returnx; }             Public voidSetX (T x) { This. x =x; }             PublicT GetY () {returny; }             Public voidsety (T y) { This. y =y; }        }         

When we create an object for:point<double> p = new point<double> (); , the t here represents a double.

Example 2:

The T and S here are based on the type of the future user using the Point class.

 Public classPoint<t,s> {            PrivateT x; PrivateS y;  PublicT GetX () {returnx; }             Public voidSetX (T x) { This. x =x; }             PublicS GetY () {returny; }             Public voidsety (S y) { This. y =y; }        } 

When we create an object for:point<string,integer> p = new point<string,integer> (); , the t of this is string,s is of type integer.

Three, generic interface

A generic interface is an interface that has one or more types of variables .

Example:

 Public Interface Action<t,u>{              void  dosomething (T t,u U);          }            Public class Actiontest implements action<string,date>{              publicvoid  DoSomething (String str,date Date) {                  System.  out . println (str);                  System.  out . println (date);              }          }            

Iv. generic methods

A generic method is simply declaring a generic on a method .

 Public class test{            publicvoid  run1 (T-t)                        {            }public <T>  t Run2 (T t) {                return  t;            }              Public void run3 (T t,s S) {                    }        }

Five, wildcard characters

Generics increase the complexity of types in Java, such as List<string>, list<integer>, list<object>, and so on, which are different types.

// Compile error         // Although        the list list = new ArrayList () is correct // Although object is the parent type        of string // but the following code compiles the Times wrong, because generics        are used New

Generic ? is a wildcard character, which can represent the parent type of all generics, the collection element can be any type, this meaningless, is generally the method, just to illustrate the usage.
list<?> list = new arraylist< any > ();

// the list can then point to any generic list type collection Object         Public void Test (list<?> List) {            // Compile error because we do not know what type List.add is represented            ( 1 );
// compiled by for (Object o:list) { System. out . println (o); } }

Note: Wildcards can only be used when a generic variable is declared .

VI. extends and Super keywords in generics

In generics, you can use the extends and Super keywords to represent the upper and lower bounds of a generic parameter passed by a future user .

6.1, the use of extends keywords

Example 1: Using extends when declaring generic classes and generic interfaces

 Public classPoint<t extends Number> {            PrivateT x; PrivateT y; }         Public classPoint<t extends Number,s> {            PrivateT x; PrivateS y; }         Public InterfaceAction<t extends Person> {             Public voiddosomething (T t); For example, use extends when declaring a generic method Public<t extends Action>voidrun (T t) {}

Example 2: Using extends when declaring a generic method

 Public void run (T t) {        }        

Example 3: Using extends when declaring a generic type variable

New Arraylist<integer>();        ListNew arraylist<long>();        ListNew arraylist<double>();         // Compile error        New Arraylist<string>();                For example        :publicvoid test (list<? extends number> List)                {     }

6.2. Use of super keyword

Example 1:

// Compile error         // cannot use Super        when declaring a generic class or generic interface  Public class Point<t Super number> {            }        publicinterface action<t Super number> {            }        // compile error         / / Declare generic method cannot use Super         publicvoid  run2 (T t) {                }     

Example 2: Using super When declaring a generic type variable

//compiled bylist<? Super Number> List1 =NewArraylist<object>(); List<? Super Student> List2 =NewArraylist<object>(); List<? Super Student> List3 =NewArraylist<person>(); //compiled by         Public voidTest (LIST&LT;? Super Number>list) {                }                //compiled by         Public voidTest (LIST&LT;? Super Student>list) {                }

Summarize:

Arraylist<t> al=new arraylist<t> (); Specifies that the collection element can only be of type T
Arraylist<?> al=new arraylist<?> (); A collection element can be any type, which is meaningless, usually in a method, just to illustrate usage
arraylist<? Extends e> al=new arraylist<? Extends E> ();
Limitations of generics:
? Extends e: Receives subtype of e type or E.
? Super E: Receives the type E or the parent of E.

Vii. & in the generic type

Use & To add multiple qualifiers to a generic type 

     Public classa{} Publicinerface b{}//whether the qualification is a class or an interface, unification uses the keyword extends//multiple qualifiers can be given using the & symbol//If an existing interface is qualified with a class, then the class must have only one, and the first place         Public classPoint<t extends A&b> {            }        classSub extends A implements b{} main://Compile ErrorPoint<a> p =NewPoint<a>(); Point<B> p =NewPoint<b>(); //compiled byPoint<sub> p =NewPoint<sub> ();

Summary: We can observe the declaration of the Map interface and its methods in the API

Public interface Map<k,v>{public V get (Object key);p ublic set<map.entry<k,v>> entryset ();p ublic Set <K> KeySet ();p ublic void Putall (map<? extends K,? extends v> m);..}   

  

Feel good to point a "recommended" Oh!

Javase (ix)-Generic (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.