A little summary of Java generics in-depth understanding

Source: Internet
Author: User
Tags comparable throwable

1, what is the generic type

First, the essence of generics is type parameterization , the popular saying is to use a variable to represent the type, the type can be string,integer and so on indeterminate, indicating acceptable type , the principle is similar to the following code

int // declares that a variable is not assigned a value, and pattern can be thought ofas generic pattern = 4 = 5; // 4 and 5 can be thought of As String and integer

The specific form of generics is seen in generic classes, generic methods

* The generic class form is as follows

class Test<t>{    private  T t;    Test (T t)    {        this. T = t;    }       Public   T Gett ()    {        return  t;    }      Public void sett (t t)    {        this. T = t;    }} 

* Generic Method Example code is as follows

 Public void Show () {    operation about T ...}

The generic parameter type declaration must precede the return type

2, why to introduce generics, that is, the advantages of generics and object

Since generics can accept more than one parameter, and object can be cast to any type by forcing a type conversion, since both have the same effect, why introduce generics?

Solution: Generics can improve security by advancing the error of using object to compile, rather than after it has been run. Examples of ArrayList with generics and non-generic ArrayList are illustrated below

Code Listing 1:

ArrayList al = new ArrayList () al.add ("Hello"); Al.add (4);//Auto-boxing String S1 = (string) al.get (0); String s2 = (string) al.get (1);//no problem at compile time, but there is a problem at run time  

When you first declare a ArrayList with no generics, its default primitive type is an object array, and since it is an object type, you can accept the assignment of any data, so there is no problem at compile time, but at run time, the integer strongly turns into string, There will surely be classcastexception. Therefore, the introduction of generics enhances security by advancing the class conversion exception to the compile time.

3. Type Erase and original type

* Origin of type Erase

Generics are not present in Java virtual machines, generics are just a mechanism created to improve the Java system, increase programmer convenience, and security, and the generic types in the Java Virtual machine are deterministic, and after the generic code is written, the generic parameter types are erased in Java virtual. Instead of using the corresponding deterministic type, this action is called type Erasure, and the type used for the substitution is called the original type, which is typically replaced by the first qualified type during the type erase, and object is used without qualification.

* Translation of generic classes

generic class (without generic qualification) code:

class Test<t>{    private  T t;      Public void Show (T t)    {    }}

The original type of the virtual machine after translation:

class test{    private  Object t;      Public void Show (Object t)    {            }}

Generic class (with generic qualification) code:

class extends Comparable>{    private  T t;      Public void Show (T t)    {    }}

The original type of the virtual machine after translation:

class test{    private  comparable t;      Public void Show (Comparable t)    {            }}

* Translation of generic methods

class Test<t>{    private  T t;      Public void Show (T t)    {    }}classextends test<string>{    private  String t;      Public void Show (String t)    {            }}

Because Testdemo inherits Test<string>, but test also has a public void Show (Object t) after the type erase, which is overloaded with the show (String T), but is not intended to show ( Object t),

Therefore, in the virtual machine translation generic method, the bridge method is introduced, and another method is called in the show (Object t) after the type erase, the code is as follows:

 Public void Show (Object t) {    Show ((String) t);}

4. Generic Limit

* Generic qualification is passed? (wildcard character) to achieve, that can accept any type, there must be someone in doubt, that? and T (when used separately) what is the difference, in fact, the difference is not very large, only in the use of parameter types.

For example:

 Public void Print (arraylist<?> al) {    Iterator<?> it = al.iterator ();      while (It.hasnext ())    {        System.out.println (In.next ());    }
}

publicvoid print (arraylist<t> al) { Iterator<T> it = al.iterator (); while(It.hasnext ()) { = It.next (); // The difference is here, T can be used as a type, and? Can only be received as any type of System.out.println (t); }}

*? Extends SomeClass this qualification, which means that only the SomeClass and its subclass types can be received, so-called "caps"

*? Super SomeClass this qualification, stating that only the SomeClass and its parent type can be received, so-called "lower bound"

A little bit of an example? Extends SomeClass illustrate one way to apply this type of qualification

Since a generic parameter type can represent any type of class, how do you ensure that the CompareTo method is defined in the T class if T is to refer to the CompareTo method? Use the following code:

 Public extends Comparable> Shwo (t A, T b) {    int num = A.compareto (b);}

This is used to qualify the T type to inherit from comparable, because the T type can call the CompareTo method.

* can have more than one type qualification, for example:

extends Comparable & Serializable>

Why do you write comparable in front of this writing method? Because of the problem of type erasure, the original type is replaced by comparable, so writing in front of a generic method that has this type in the class is put in front, avoiding the coercion of the type when invoking the method, and improving efficiency.

class extends Comparable & serializable>{    private  T lower;     Private T Upper;      Public // here is the use of comparable method, so the comparable written in front, type erase after the comparable, if the serializable, but also forced type conversion, otherwise you cannot use the CompareTo method.      {        int a = First.compareto (second);        ...    }}

* About the "inheritance" error of generic type qualification

There are always some people who mistakenly take the restriction of a type as inheritance, such as:

// The type is like this extends Person>// Then such error occurs new arraylist<student> ();

Here <person> <Student> as a generic means the receiver type of the ArrayList container, using a simple example to illustrate

ArrayList is a large farm,<person> shows that he is able to receive animals, whereas the new statement above generates a farm that can only receive pigs (arraylist<student>), That is, a large farm has been built into a pig farm, if the succession of large-scale farms will certainly be able to accept dogs, sheep .... , but now it's built into a pig farm, can you accept other animals? So this must be the wrong usage! In short, the type parameters on both sides of the generic new must be identical.

5, some basic rules of the generic constraints

* Generic type parameter must be a reference to the class and cannot be used with the base type (int, short, long, byte, float, double, char, Boolean)

* Generics are parameterized for types and can be used as different types when used (this is explained in detail when speaking a generic class)

* Generic type parameters can have multiple, code examples are as follows:

 Public void Show () {        coding operation ...    }                

* Generics can use extends, super,? (wildcard character) to qualify a type parameter

* Because of type erasure, run-time type queries are only available for primitive types, such as instanceof, GetClass (), coercion type conversions, a instanceof (pair<employe>), and a instanceof after type erasure Pair, so some of the operations above run in the virtual machine operation is the original type operation, no matter how unreal writing, can not escape the type erase, because there is no generics in the virtual machine species.

* Cannot create an array of parameterized types

For example, write the following code:

New // ERROR // let object[] t point to table object[] t = table; // add an object to T New Pair<employe>(); // the key error points String s = table[0];

Since object can receive any type, there is no problem when the new pari<employe> is stored inside, but when the classcastexception is taken out, it is not possible to create an array of parameterized types.

* Cannot instantiate type variables, and cannot appear similar to the following code

New T (); // or T.class

Since the type is erased, it is object t = new object (); incompatible with intent, that is, the intention is certainly not to invoke object.

* Parameter types can no longer be present in a static domain or method

For example, the following error code

 class  test<t>{ private  static  T example; //    error  public  static  void  showexample () error   {action about T ...}  public  static  T showexample () Span style= "color: #008000;"         >// error   {action about T .... }}    

The first method is a normal method with a return type of T, not a generic method, which is the same as using a non-static parameter in a static method, where the static method is in memory prior to the object, so the type of T cannot be determined at compile time, and the cannot make a static must appear. Reference to a non_static reference "this is a similar error.

But this code is right.

class Test<t>{publicstatic <T> T Show ()    {        action    }}

Because the static method here is a generic method, you can use the.

* Instances of generic classes cannot be thrown or captured

+ Cannot throw a generic class object that cannot be caught

The + generic class cannot extend throwable, note that the class cannot inherit throwable, and the qualification of the type parameter is still possible.

The +catch clause cannot use a type variable, as in the following code

Try {    ....} Catch // Error {    ...}

* Conflict after type erase note

For example:

class Pair<t>{    publicboolean//error    {        ....    }}

The reason for the error here cannot exist for the same method, after the type erasure, the method of pair is, public boolean equals (object value), which conflicts with the Equals (object obj) inherited from Object.class.

* A class cannot be a subclass of two interface types, and these two interfaces are different parameterization of the same interface.

For example:

class implements coparable<calendar>{}classextendsimplements//  Error

When the type erase, calendar implementation is comparable, and GregorianCalendar inherit the calendar, and to implement comparable, inevitable error!

———————————————————————————————————————————————————————————————————————————————

Let's summarize here.

A little summary of Java generics in-depth understanding

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.