java core technology to read 10 (g) - generic programming

Benefits type of the parameter
before the increase in Java generics class, generic programming is inheritance achieve. ArrayList class only to maintain an array of Object references, use ArratList there are two problems, one is the need to force conversion to get the value, and the other will produce an error when cast.
Use type parameters to solve:

ArrayList<String> files = new ArrayList<String>() 

String String object represented as where, in addition, it can be automatically extended array list than arrays (String []) is better, because.
1. Define generic class
2. The generic method definition, can also be defined in the general class

Generics also requires certain restrictions, such as limiting the generic parameter must implement an interface,

public static <T extends Comparab1e> T min (T[] a) . . .

Generic code and virtual machine
compiler to translate this method call into two virtual machine instructions:

Pair<Employee> buddies =...
Employee buddy = buddies.getFirstO;

• call to the original method of Pair.getFirst. Original method refers to a generic virtual machine parameters have been erased and converted into Object or specify the superclass
• The Object type cast to Employee return type.

Virtual machine without generics, only ordinary classes and methods.
All types of parameters are defined by their type of replacement.
• Bridge methods are synthesized to keep the polymorphism.
In order to maintain the type of security, if necessary, insert cast.

Type parameter constraints and limitations

  1. Examples of the basic types can not use the type of parameter, type erasure reasons, only Object Type
  2. When trying to query whether an object belongs to a generic type, if using instanceof will get a compiler error, if the cast will get a warning.
  3. Arrays can not create a parameterized type, Pair [] table = new Pair [10]; // Error
  4. Examples of types becomes not opposed
  5. We can not be constructed generic array
  6. Prohibit the use of static fields and methods with type variables
  7. Not throw or capture instance of a generic class

Generic type of inheritance rules
no inheritance relationship between generic type, there is no reference to the relationship, but can always be parameterized type to a primitive type

Wildcards

Pair<? extends Employee

It denotes any generic Pair type whose type parameter is a subclass of Employee, such as Pair
Pair <? Super Manager>
denotes any generic Pair type whose type parameter is the Manager of the superclass, such as Pair Pair

Wildcards can be defined with a supertype written into the generic object with wildcard subtype defined can be read from the generic object.

Published 15 original articles · won praise 1 · views 129

Guess you like

Origin blog.csdn.net/qq_17236715/article/details/104950974