泛型核心目的:类型参数化,在编译期做类型检查,避免强制类型转换。
核心思想:把类型当作参数传给类/接口/方法。
1. 基础概念
<T>:类型参数,T只是占位符,常用约定字母TType 任意类型EElement 集合元素K,VKey,Value 键值对RReturn 返回值类型
- 编译擦除:泛型只存在编译阶段,运行时字节码没有泛型信息。
- 现代写法:菱形语法
<>,创建对象时可以省略尖括号内类型,例如List<String> a=new ArrayList<>()。
2. 泛型类
定义类的时候指定类型参数。
// 泛型类,T代表存储的数据类型
class Box<T> {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
public class GenericDemo {
public static void main(String[] args) {
Box<String> strBox = new Box<>();
strBox.setValue("Hello Generic");
String s = strBox.getValue(); // 无需强转
Box<Integer> intBox = new Box<>();
intBox.setValue(100);
Integer num = intBox.getValue();
System.out.println(s);
System.out.println(num);
}
}
3. 泛型方法
方法上单独声明类型参数,可以放在普通类里,不需要类是泛型类。
类型参数写在方法返回值前面
<T>
class Util {
// 泛型方法
public static <T> void print(T item) {
System.out.println(item);
}
// 返回泛型
public static <T> T getFirst(T item) {
return item;
}
}
public class GenericDemo {
public static void main(String[] args) {
Util.print("test");
Util.print(999);
String res = Util.getFirst("abc");
System.out.println(res);
}
}
3. 有界类型(限定泛型范围 extends)
限制T只能是某个类的子类 / 实现某个接口
T extends Number:T必须是Number或者Number子类(Integer, Double等)
class NumBox<T extends Number> {
private T num;
public void setNum(T num) { this.num = num; }
public T getNum() { return num; }
}
public class GenericDemo {
public static void main(String[] args) {
NumBox<Integer> ib = new NumBox<>();
ib.setNum(10);
NumBox<Double> db = new NumBox<>();
db.setNum(3.14);
// NumBox<String> sb = new NumBox<>(); // 编译报错,String不是Number子类
System.out.println(ib.getNum());
System.out.println(db.getNum());
}
}
多边界写法:
<T extends Number & Comparable<T>>
4. 泛型接口
interface Storage<T> {
void save(T data);
T read();
}
public class StringStorage<T> implements Storage<T>
{
T data;
public void save(T x) {
data=x;
System.out.println("save: " + data);
}
public T read() {
return data;
}
}
public class App
{
public static void main(String[] args) throws Exception
{
Storage<String> a=new StringStorage<>();
a.save("666");
System.out.println(a.read());
}
}
不能用基本类型:Box<int> ❌,必须包装类 Box<Integer> ✅
含ai生成、作者整理的内容。
浙公网安备 33010602011771号