Java Core Technology Volume 16. Java Generic Programming

Source: Internet
Author: User
Tags addall comparable wrapper

Generic programming

Generic programming: Code written can be reused by many different types of objects.

Type parameter: Used <String> , which can be omitted because it can be inferred from the type of the variable. Type parameters make the program more readable and secure.

Wildcard types: Very abstract, let the builders of the library write a method as flexible as possible.

Defining a simple generic class

A generic class is a class that has one or more type variables.

//reference type variable T, can have more than one type variable, public class Pair<t, u>{...} Public classpair<t> {//class-defined type variable the return type of the method and the type of the domain and local variables    PrivateT first;PrivateT second; Public Pair() {first =NULL; Second =NULL; } Public Pair(t first, T second) { This. First= First; This.Second= Second; } PublicTGetFirst(){returnFirst } PublicTGetsecond(){returnSecond } Public void Setfirst(T newvalue)    {first = newvalue; } Public void Setsecond(T newvalue)    {second = newvalue; }}

When you instantiate a class, you can instantiate the type by adding a specific type substitution type variable.

//用具体的类型替换类型变量就可以实例化泛型类型//此时,构造器和方法的类型都会赋予getFirstgetSecond()voidsetFirst(String)voidsetSecond(String)

Multiple types of variables can be as follows:

public class Pair<T, U>{...}

Structure at invocation:

Pair pair = new Pair<String>();

Generics can be seen as a common class of factories.

Generic methods

To define a simple method with type parameters

class Arraylg{    publicstaticgetMiddle(T... a){        return a[a.length2];        }}

To invoke a generic method:

String middle = Arraylg.<String>getMiddle("John","Q","Public");
Qualification of type variables

Sometimes a class or method needs to constrain a variable to implement a function that sets a qualified implementation on a type variable T:

<T extends BoundingType>

Multiple limits

<T extends Comparable & Serializable>

At this point, you can limit the type T to implementing these interfaces.

Generic code and virtual machines

The virtual machine does not have a generic type object, and all objects belong to the normal class.

Type Erase

generic type, which automatically provides a corresponding primitive type : Deletes the generic type name after the type parameter. Erase The type variable and replace it with the qualified type (the variable with no qualified name with Object).

After the compiler, generics do not exist in the virtual machine.

Translating generic expressions
Pair<Employee> buddies = ...;Employee buddy = buddies.getFirst();

Compiler bar This method call translates to two virtual machine directives:

    • The call to the original method Pair.getfirst.
    • Forces the returned Object type to be convertible to the Employee type.
Translating generic methods
publicstaticextendsmin(T[] a)publicstaticmin(Comparable[] a)

Type parameter T erase, leaving the qualified type compatable.

Type erasure conflicts with polymorphism to generate a bridge method in the class:

public void setSecong(Object second) { setSecond((Date) second); }

The fact of the Java Generics transformation:

    • There are no generics in the virtual machine, only ordinary classes and methods.
    • All type parameters are replaced with their qualified type.
    • The bridge method is synthesized to maintain polymorphism.
    • To preserve type safety, insert coercion type conversions, if necessary.
Constraints and limitations cannot instantiate a type parameter with a base type

Wrapper types can be used, and independent classes and methods can be used to handle them if the wrapper type cannot accept replacements

Run-time type queries are only appropriate for the original type

Whenever you use instanceof for generics, you get a compiler error;

The cast expression for a generic type will see a compilation warning.

The GetClass method always returns the original type.

Pair<String> stringPair = ...;Pair<Employee> employeePair = ...;stringPair.getClass() == employeePair.getClass();ifinstanceof//Error//Warning

The result is true to return Pair.class

Cannot create an array of parameterized types
Pair<String>[] table = new Pair<String>[10];//error

You can declare an array of wildcard types, and then type-convert:

new Pair<?>[10];

But the results are not safe.
Security methods:

ArrayList<Pair<String>>
Varargs Warning

Pass an instance of a generic type to a method with a variable number of arguments:

publicstaticvoidaddAll(Collection<T> coll, T... ts){    for (t : ts) coll.add(t);}

A TS array is required, but he violates the rules and gets a warning that the warning can be removed by commenting:

@SafeVarargspublicstaticvoidaddAll(Collection<T> coll, T... ts)

You can now provide a generic type to invoke this method.

Cannot instantiate type variable

Illegal:public Pair() { first = new T(); second = new T(); } // Error

The same reflection call is also illegal:fisrt = T.class.newInstance(); // Error

Cannot construct a generic array

Illegal:T[] mm = new T[2];

Invalid type variable in static context of generic class

You cannot reference a type variable in a static field or method.

private static T s; // Errorpublic static T getS(){...}; // Error
You cannot throw or catch instances of a generic class

Illegal:public class Problem<T> extends Exception { /*...*/ } // Error

A type variable cannot be used in a catch clause.

Using a type variable in the exception specification is allowed:public static <T extends Throwable> void doWork(T t) throws T // OK

You can eliminate the check for checked exceptions

Exception handling specifies that a processor must be provided for all the exceptions being checked. However, generics can be used to eliminate this limitation.

Notice the conflict after erasing

When a generic type is erased, the condition that caused the conflict cannot be created.

To support the erase transformation, you need to force the restriction that a class or type variable cannot be a subclass of two interface types at the same time, and the two interfaces are different parameterization of the same interface.

Illegal:

classimplements... }classextendsimplements... //Error

Managerwill be implemented Comparable<Employee> and Comparable<Manager> , this is different parameterization of the same interface.

Inheritance rules for generic types

Pair<Manager>is not Pair<Employee> a child class. You can convert a parameter type to an original type, but it produces a type error.

Whatever the relationship between S and T, it has nothing to do with the Pair<Manager> Pair<Employee> basics.

Wildcard type wildcard character concept

A wildcard type that allows the type parameter to change.

Pair<? extends Employee>

Is any generic Pair type whose type parameter is the Employee subclass.

Pair<Manager>And Pair<Employee> is Pair<? extends Employee> the subtype.

Super-type qualification of wildcard characters

Super-type Qualification:

? super Manager

This wildcard is limited to all of the Manager's hyper-types.

public static <T extends Comparable<T>> T min(T[] a)public static <T extends Comparable<? super T>> T min(T[] a) //用于处理需要泛型类型超类型的情况
No-limit-pass fit

Unqualified wildcard characters:Pair<?>

This class has the following methods:

? getFirst()void setFirst(?)

GetFirst can give an Object;

The Setfirst method cannot be called, nor can it be called with Object. But it can be called setFirst(null) .

Wildcard capture

Wildcard characters are not type variables and cannot be used ? as a type in writing code.

Solution:

publicstaticvoidswapHelper(Pair<T> p){    T t = p.getFirst();    p.setFirst(p.getSecond();    p.setSecond(t);}publicstaticvoidswap(Pair<?> p){    swapHelper(p);}

The Swaphelper method's parameter T captures a wildcard character. He doesn't know what kind of wildcard it is, but it's a definite type.

Reflection and generic generic class

The class is generic and is the String.class object of a Class<String> class (the only object).

If the given type is indeed a subtype of T, the cast method returns an object that is now declared as type T, or throws an Badcastexception exception.

If this class is not an enum class or an array of enum values of type T, the getEnumConstants method returns NULL.

getConstructorgetdeclaredConstructorreturns an object with the method Constructor<T> . The Constructor class has also become generic so that newInstance the method has a correct return type.

API:

T newInstance()T cast(Object obj)T[] getEnumConstants()Class<? super T> getSuperclass()Constructor<T> getConstructor<Class... parameterTypes)Constructor<T> getDeclaredConstructor<Class... parameterTypes)//java.lang.reflect.Constructor<T>T newInstance(Object... parameters)
Use Class<T>parameter for type matching
publicstaticmakePair(classthrows InstantiationException, IllegalAccessException {    returnnew Pair<>(c.newInstance(), c.newInstance());}

Call

makePair(Employee.class);

The type parameter T matches the Employee.

Generic type information in a virtual machine

You can use the reflection API to determine:

    • This generic method has a type parameter called T.
    • This type parameter has a subclass qualification, which is itself a generic type.
    • This qualified type has a wildcard parameter.
    • This wildcard parameter has a superclass qualification.
    • This generic method has a generic array parameter.

Java Core Technology Volume 16. Java Generic Programming

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.