Reference ---- "Java core technology."
I. Overview
Before increasing java generic design is the use of the general procedure of inheritance to implement the method of the type parameter is set to the base class, such a method would be universal, for example, the following
class ArrayList {
private Object[] elementData;
public Object get(int i) {
}
public void add(Object o) {
}
}
Such a realization that there are two problems: ① when acquiring a value must be cast; ② where you can add any Object object, there is no error checking. Here we assumed StringValue to store String collection, ArrayList just maintain an array of Object references, we can not stop will join type Integer to our String set when we need the data, you need to get the Object object into our desired type , if you add an unexpected type to the collection, no errors at compile time, but abnormal ClassCastException at runtime will be reported.
Second, the benefits of generic nature
The benefits of using generics
① type safety
② eliminate casts
nature generic
① the object / collection inside the element type defer to create a collection when
② type parameterization
Third, the generic format
Data type <generic parameter> = new Object data type <generic parameter>;
ArrayList<String> list = new ArrayList<String>();
There is a type inference after jdk1.7, i.e. the back may be omitted new generic type
ArrayList<String> list = new ArrayList<>();
ArrayList<String> list = new ArrayList();
For type inference, look to the left. E.g
ArrayList list = new ArrayList<String>();
list.add(1);
list.add("String");
Here without error, String where there is no generic parameters of a role.
Fourth, the generic class
Is a generic class having one or more types of Class variables
basic syntax: class Class Name <Generic Identifier>
public class Pair<T> {
T first;
T second;
Pair(T first , T second){
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getSecond() {
return second;
}
public void setSecond(T second) {
this.second = second;
}
}
Five generic interface
Generic interface with generic class using substantially the same
interface GenericType<T> {
T T; //Error
}
In the interface, all instance fields are initialized to public static final
all public methods are the
variables in the above example is not so appear in the type variable, because there are immutable interfaces.
Sixth, generic method
public static <T> T getMiddle(T[] t) {
return t[t.length /2];
}
In use, the parameters of the type
String[] str = {"A" , "B" ,"C"};
String middle = Generic.<String>getMiddle(str);
Seven generics wildcards?
1. ? Unbounded wildcard
-
Why should there be? Unbounded wildcard
Example: there is a parent class Animal and several sub-categories, such as dogs, cats, etc., and now I need a list of animals. The initial idea is:
List<Animal> listAnimals
But the right idea:
List<? extends Animal> listAnimals
Wildcards In fact, when you declare a local variable is meaningless, but when you declare a method as a parameter, it is very important.
package cn.ArrayList;
import java.util.ArrayList;
import java.util.List;
/**
* @author四五又十
* @create 2020/2/13 20:17
*/
public class demo2 {
static int countLegs (List<? extends Animal > animals ) {
int retVal = 0;
for ( Animal animal : animals ){
}
return retVal;
}
static int countLegs1 (List< Animal > animals ){
int retVal = 0;
for ( Animal animal : animals ){
}
return retVal;
}
public static void main(String[] args) {
List<Dog> dogs = new ArrayList<>();
// 不会报错
countLegs( dogs );
// 报错
countLegs1(dogs);
}
}
class Animal{
}
class Dog extends Animal{
}
Error message: Error: (32, 20) java: incompatible types: java.util.List <cn.ArrayList.Dog> can not be converted into java.util.List <cn.ArrayList.Animal>
? T and the difference between:
? And T have said the type of uncertainty, the difference is that we can operate on the T, but? Not work
In other words, generic wildcard approach is meaningful, T is a certain type, commonly used to define a generic class and generic methods? Type is an uncertain, generally for a generic method and calling code parameter, a generic definition of classes and methods can not be used.
2.< ? extends E>
-
The concept: <? Extends E> is an upper bound wildcard, use extends keyword statement, represents the parameterized type may be specified by type or subtype of class.
This has two advantages:
- If the incoming type is not a subclass of E or E, the compiler unsuccessful
- Generics can use E method, or else have to turn into a strong E to use
- If the incoming type is not a subclass of E or E, the compiler unsuccessful
3.< ? super E>
-
concept:
<? Super E> is a lower bound wildcard represents a parameterized type may be specified by type, or is this type of parent type, until Object
Eight generic code and virtual machine
No generic type of object on a virtual machine - all objects belong to the general category
1. type erasure
Whenever you define a generic type, automatically it provides a corresponding original type. Delete the original type of the generic type name is the name of the type parameter. Type variable erased and replaced defined type (type indefinite use Object). The above example, the original type of generic class Pair
public class Pair {
Object first;
Object second;
Pair(Object first , Object second){
this.first = first;
this.second = second;
}
public Object getFirst() {
return first;
}
public void setFirst(Object first) {
this.first = first;
}
public Object getSecond() {
return second;
}
public void setSecond(Object second) {
this.second = second;
}
}
2. Translation generic expression, generic method
When a program calls a generic method, if the return type erase, the compiler inserts cast.
Pair<Employee> buddies = ...
Employee boddy = buddies.getFirst();
After erasing getFirst () return type, the compiler automatically inserts Employee casts. Is to say, the compiler will translate to call this method for two virtual machine instructions:
(1) Pair.getFirst original method () calls
(2) will return Object type cast to type Employee
In short, you need to know about java generics conversion:
① on the virtual machine without generics, only ordinary classes and methods
② all types of arguments are used to replace their limited type of
bridge approach is to keep the multi-state synthesis
to maintain the type of security necessary when the cast insert