Types are: simple types and complex types, and the introduction of generics has made the complex types more granular;
-
Now list, list is, 两种不同的类型 and 无继承 relationship;
-
The benefits of generics are as follows:
Start version
public void write(Integer i, Integer[] ia);public void write(Double d, Double[] da);
Generic version
public <T> void write(T t, T[] ta);
Simple code.
Defining generics
-
1. Define behind the class
Follow the 类名 back.
class TestClassDefine<T, S extends T>{}
Defines generic t, S, and S inherits T
-
2. Define after method 装饰符
Immediately 修饰符 following (public)
public <T, S extends T> T testGenericMethodDefine(T t, S s){}
Defines generic t, S, and S inherits T
Instantiating generics
- 1.
定义在类 Generics on instantiation
First statement 类变量 or 实例化时 . For example
List<String> list; list = new ArrayList<String>;
Second 继承类 or 实现接口 time. For example
class MyList<E> extends ArrayList<E> implements List<E> {...}
- 2.
定义方法 Generics on instantiation
When the generic method is called, the compiler automatically assigns the value when the time is 类型参数(泛型) not successfully assigned to the Times compilation error
wildcard character (?)
The above has generics 定义 and 赋值 ; When in 赋值 , the above section says that the assignment is for 具体类型 , when the type 不确定 of assignment, we use 通配符(?) instead of:
Such as
List<?> unknownList; List<? extends Number> unknownNumberList; List<? super Integer> unknownBaseLineIntgerList;
In the Java Collection framework, for the container class where the parameter value is, 未知类型 只能 read the element, add the 不能 element to it,
Because the type is unknown, the compiler does not recognize that the type of the element being added and the type of the container is compatible, the only exception being null
T-and in Java generics?