概述
泛型,即参数化类型,将具体的类型定义成参数形式(类型形参)。是 JDK 5 中引入的一个新特性,泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型,泛型只存在于编译期间,编译后类型会被擦除,被Oject代替。
// 基础语法
class 类型名<泛型标示符:可以随意写合法的字符>{
private 泛型标识符 var;
}
复制代码
类型形参的规则
-
T : List 指定类型
-
? : List<? extend E> -- 接受E或者E的子类 List<? super E> -- 接受E或者E的父类
-
Object : 任意类型,好像没有什么意思。
3个使用方式
泛型类
直接上例子
public class Box<T> {
private T object;
public void set(T object) {
this.object = object;
}
public T get() {
return object;
}
public static void main(String[] args) {
Box<String> box1 = new Box<>();
box1.set("hello world ~");
System.out.println(box1.get());
}
}
复制代码
泛型接口
直接上例子
public interface Mymap<K, V> {
public K getKey();
public V getValue();
}
public class MymapImpl<K, V> implements Mymap<K, V> {
private K key;
private V value;
public MymapImpl(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public static void main(String[] args) {
Mymap<String, Integer> mp1 = new MymapImpl<String, Integer>("ESds", 23);
Mymap<String, String> mp2 = new MymapImpl<String, String>("hello", "world");
Mymap<Integer, Integer> mp3 = new MymapImpl<Integer, Integer>(232, 888);
}
}
复制代码
泛型方法
直接上例子
public class Box<T> {
private T object;
public void set(T object) {
this.object = object;
}
public T get() {
return object;
}
// 定义泛型方法
public <T1> void printBox(T1 x) {
T1 m = x;
System.out.println("This box is:" + m);
}
public static void main(String[] args) {
Box<String> box1 = new Box<>();
Box<Integer> box2 = new Box<>();
box1.printBox(box2);
}
}
复制代码
类型擦除
编译器虽然会在编译过程中移除参数的类型信息,但是会保证类或方法内部参数类型的一致性。
// 泛型"擦除"
// 编译器虽然会在编译过程中移除参数的类型信息,但是会保证类或方法内部参数类型的一致性。
Class<?> boxClass1 = new Box<String>().getClass();
Class<?> boxClass2 = new Box<Long>().getClass();
System.out.println(boxClass1);
System.out.println(boxClass2);
输出:
class day13.Box
class day13.Box
复制代码