作者:拔剑少年
简书地址:https://www.jianshu.com/u/dad4d9675892
博客地址:https://it18monkey.github.io
转载请注明出处
泛型的好处
编译时期的强类型检查。有利于提早发现问题,解决问题。
不用再使用类型强转。
能够利用泛型编写简单易读的通用代码。
泛型的使用
泛型通常命名规则
E - Element
K - Key
N - Number
T - Type
V - Value
S,U,V 等等。- 第二,第三,第四类型。
泛型类的定义和使用。
以最常用的
Arraylist
为例,我们看下它的定义和使用。当我实例化时在<>
中传入的类型为Integer
时,集合中就无法再放入其他类型的元素了,从集合中取得元素时也不用再强转。(注意:泛型不支持基本类型,但是我们可以使用它的包装类型)1
2
3
4
5
6
7//定义
public class ArrayList<E>{}
//使用
ArrayList<Integer> list=new ArrayList<>();
list.add(1);
list.add(2l);//编译错误,无法插入Long类型
Integer integer=list.get(0);//能够直接确定取得的是Integer类型泛型方法。
声明方法和泛型类相似。
作用域仅限于声明的方法内。
静态方法,非静态方法,构造方法都可以使用。
类型参数区段必须出现在方法返回类型之前。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/**
* 泛型构造方法格式
* @param t
* @param <T>
*/
public <T> Generics(T t) {
}
/**
* 非静态泛型方法格式
* @param t
* @param <T>
* @return
*/
public <T> T getNonStatic(T t) {
}
/**
* 静态泛型方法格式
* @param t
* @param <T>
*/
public static <T> voTid getStatic(T t) {
}类型限定。关键字
extends
,限制传入的类型参数必须为指定的类型或其子类型。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19/**
* 单个类型限定
* @param t
* @param <V>
*/
public static <V extends Integer> void singleBondedType(V t) {
System.out.println(t.intValue());
}
/**
* 多个类型限定,需要同时满足条件。
* 类型限定声明中类需要声明在接口前面
* @param t
* @param <V>
*/
public static <V extends Integer & Comparator> void multipleBondedType(V t) {
System.out.println(t.intValue());
System.out.println(t.compare(1,2));
}通配符(Wildcards)
向上有界通配符(Upper Bounded Wildcards)
无界通配符(Unbounded Wildcards)
向下有界通配符(Lower Bounded Wildcards)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/**
* 上有界通配符
* @param list
*/
public static void upperBoundedWildcards(List<? extends String> list){
}
/**
* 无界通配符
* @param list
*/
public static void unboundedWildcards(List<?> list){
}
/**
* 下有界通配符
* @param list
*/
public static void lowerBoundedWildcards(List<? super Integer> list){
}ps: 你可以用通配符指定一个上界,也可以指定一个下界,但不能同时指定。
泛型的限制
不接受基本类型当作参数。
不能通过new泛型来实例化对象,但是可以通过反射来实现。
不能声明静态泛型变量。
不能对泛型参数使用
cast
或instanceof
。不能创建泛型型数组,比如
1
List<Integer>[] arrayOfLists = new List<Integer>[2]; // 编译错误
由于类型擦除机制,不能通过泛型重载方法。
1
2
3//编译错误
public void print(Set<String> strSet) { }
public void print(Set<Integer> intSet) { }