Java Generic parsing

Source: Internet
Author: User

1. Overview
Before introducing the paradigm, the Java type is divided into primitive types, complex types , where complex types are divided into arrays and classes . Once the paradigm is introduced, a complex type can be subdivided into more types.

For example, the original type List, which is now subdivided into List<object>, list<string> and so on more types. Note that now List<object> List<string> is two different types, and there is no inheritance between them, even if String inherits Object. The following code is illegal:

New Arraylist<string>();
List<Object> lo = ls;

The reason for this is that, according to the LO Declaration, the compiler allows you to add any object (such as an integer) to the lo, but this object is List<string>, which destroys the integrity of the data type.

Before introducing the paradigm, to support multiple data types in a method in a class, you need to overload the method, and after introducing the paradigm, you can solve the problem (polymorphism) and further define the relationships between multiple parameters and the return value.

e.g.

 Public void Write (Integer I, integer[] ia);  Public void Write (Double  D, double[] da);

The model version is

 Public void Write (T T, t[] ta);

2.1 defining a class with type parameters

when defining a class with a type parameter, specify the name of one or more type parameters in the <> following the life of the class , and you can also qualify the value range of the type parameter , between multiple type parameters separated by a number . After you define the type parameters, you can use the type parameters almost anywhere ( except static blocks, static properties, static methods , and so on), just as you would with a normal type. Note that the type parameters defined by the parent class cannot be inherited by the quilt class .

 Public class extends t> {     ...   }


2.2 Defining the type parameter method
When defining a method with a type parameter, specify the name of one or more type parameters in <> following the visible range decoration (for example, public), and you can also qualify the value range of the type parameter, separating the multiple type parameters with the number. After you define a type parameter, you can use the type parameter anywhere you define the method, just as you would with a normal type.
For example:

 Public extends T> t Testgenericmethoddefine (T T, s s) {     ...}

Note: Defining a method with a type parameter is primarily intended to express the relationship between multiple parameters and the return value . For example, in this example , the inheritance relationship between T and S, the type of the return value is the same as the value of the first type parameter . If you want to implement polymorphism only, use wildcard characters as a priority. The contents of the wildcard are shown below.

 Public void TestGenericMethodDefine2 (list<t> s) {     ...}

should read:

 Public void testGenericMethodDefine2 (list<? > s) {     ...}

3. Type parameter Assignment
When assigning a value to the type parameter of a class or method, all type parameters are required to be assigned values. Otherwise, you will get a compilation error.

3.1 Assigning a type parameter to a class with a type parameter
There are two ways to assign a type parameter to a class with a type parameter

The first declaration of a class variable or instantiation . For example:

list<string>new arraylist<string>;

The second inheriting class or when implementing an interface . For example

 Public class extends Implements


3.2 Assigning values to a band-type parameter method
When the generic method is called, the compiler automatically assigns a value to the type parameter when it cannot be successfully assigned to the Times compilation error. For example

  Public<T> t TestGenericMethodDefine3 (T T, list<t>list) {     ... }  Public<T> T testGenericMethodDefine4 (list<t> list1, list<t>List2)  {     ... } Number n=NULL; Integer I=NULL; Object o=NULL; Testgenericmethoddefine (n, i);//T is number, S is integerTestgenericmethoddefine (o, i);//T is object, S is integerList<Number> List1 =NULL; TestGenericMethodDefine3 (i, List1)//T is number at this timeList<Integer> List2 =NULL; TestGenericMethodDefine4 (List1, List2)//Compile Error


3.3 Wildcard characters
In the above two sections, the type parameter is given a specific value, and in addition to this, the type parameter can be given an indeterminate value. For example

List<?> unknownlist; Listextends number> unknownnumberlist; ListSuper

Note: In the Java Collection Framework, for a container class with an unknown type for the parameter value , only the element can be read , and the element cannot be added as such, because its type is unknown, Therefore, the compiler does not recognize that the type of the element being added and the type of the container are compatible, and the only exception is null.

List<string> liststring; List<?> unknownList2 == = unknownlist; // Compile Error

(1) wildcard characters with a super-type qualification can be written to generic objects, <? Super man>;
(2) wildcard characters with sub-type qualification can read < from generic object;? extends Man>.


4. Array paradigm
You can declare an array using a class with a generic parameter value, but you cannot create an array

list<integer>new arraylist<integer>[10]; // compile-time error



5. Principle of implementation

5.1. Java paradigm When compile-time technology, does not contain the generic information at run time, only the class instance contains the type parameter definition information.

Generics are implemented through front-end processing of the Java compiler called Erase (erasure). You can (basically) think of it as a source-to-source conversion that transforms the generic version into a non-generic version.
Basically, wiping out all the generic type information. All type information between the angle brackets is thrown away , so for example a list<string> type is converted to a list. All references to type variables are replaced with the upper bound of the type variable (usually object). Also, whenever the result code type is incorrect, a conversion to the appropriate type is inserted.

<T> t Badcast (T T, Object O) {         return//  unchecked warning       }

The type parameter does not exist at run time. This means that they do not add any time or space burden, which is good. Unfortunately, this also means that you cannot rely on them for type conversions.
what is the result of the following code printing?

New Arraylist<string>();       ListNew arraylist<integer>();        = = L2.getclass ());

Maybe you can say false, but you think wrong. It prints out true. Because all instances of a generic class have the same runtime Class (class)at run time, regardless of their actual type parameters. In fact, generics are called generics because they have the same behavior for all of their possible type parameters, and the same classes can be treated as many different types. As a result, the static variables and methods of a class are also shared among all instances. This is why it is not legal to use a type parameter (the type argument is a specific instance) in a static or static initialization code or when declaring and initializing a static variable.



Please see the original http://blog.csdn.net/jinuxwu/article/details/6771121




Java Generic parsing

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.