Generics in Java

Source: Internet
Author: User

Generic classes and generic methods

public class pair<t>{...}

public static <T> T Getmiddle (t[] a) {...}

public static <M> m,<v> V mycompate (M am,v av) {...}

public static <t extends comparable & serializable> Getmiddle (t[] a)
Add qualifiers, separated by &, can have multiple interfaces, if there is a class inheritance relationship, there can only be one, and must be placed in the first place

Second, generic code and virtual machine

The objects in the virtual machine are all normal class objects, no generic objects.

A generic object is first created with a type wipe to generate the original type, and the name of the original type is the generic type name after the type parameter is deleted.

public class pair{...}

public static Object Getmiddle (object[] a) {...}

public static object Mycompate (Object Am,object av) {...}

public static <comparable > Getmiddle (comparable[] a)

When a program uses generics, a type conversion is forced, converted to an instantiated type, and then processed.

For example, double inst[];getmiddle (inst), object[] will be converted to double[] first.

Third, restriction and limitation

1. Type parameters cannot be instantiated with a base type

2. Run-time type queries return only the original type

instanceof, coercion type conversion, getclass () ...

3. Instances of generic types cannot be thrown or captured

4. An array of parameterized types is not valid

pair<string>[] table = new Pare<sting>[10];//error

5. Type variables cannot be instantiated

6. Invalid type variable in static context of generic class

Iv. inheritance rules for generic types

Reference documents

"Java Core Technology Vol. 1: Fundamentals"

Generics in Java

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.