java 泛型通过类型参数在编译期锁定集合或对象的具体类型,从而消除强制类型转换。使用 <string></string> 等参数化类型声明变量后,编译器会自动处理存取时的类型检查与转换。这样既避免了运行时 classcastexception,也提升了代码的可读性。

泛型类如何定义类型参数
定义泛型类时,需在类名后添加 <t></t> 占位符。该占位符代表一个具体的类型,在使用该类时必须显式指定。例如,创建一个通用的数据容器类 DataBox<t></t>,其内部字段和方法均使用 T 作为类型。当实例化为 DataBox<integer></integer> 时,所有涉及 T 的地方都自动替换为 Integer。

public class DataBox<T> {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public static void main(String[] args) {
DataBox<String> box = new DataBox<>();
box.setValue("Hello");
String result = box.getValue(); // 无需强转
System.out.println(result);
}
}
泛型方法如何独立于类
泛型方法允许在方法签名中定义独立的类型参数,即使该方法所在的类不是泛型类。这在工具类中非常常见,如 Collections 中的静态方法。通过在返回值前添加 <t></t>,可以告诉编译器该方法将使用一个新的类型参数。调用时,编译器会根据传入的参数类型自动推断 T 的具体值,无需显式指定。
立即学习“Java免费学习笔记(深入)”;

public class GenericUtils {
public static <T> T getFirstElement(T[] array) {
if (array == null || array.length == 0) {
return null;
}
return array[0];
}
public static void main(String[] args) {
Integer[] ints = {1, 2, 3};
String[] strs = {"A", "B"};
Integer firstInt = getFirstElement(ints); // 自动推断为 Integer
String firstStr = getFirstElement(strs); // 自动推断为 String
System.out.println(firstInt + ", " + firstStr);
}
}
通配符如何解决泛型协变问题
当需要编写能接受多种泛型类型的通用方法时,直接使用具体类型会导致不兼容。例如,List<number></number> 不能直接接收 List<integer></integer>。此时应使用通配符 ? extends T 来限制上限。这表示方法可以接受任何继承自 T 的类型。在读取数据时是安全的,因为所有子类型都可以向上转型为父类型;但在写入数据时受到限制,只能写入 null。
import java.util.List;
import java.util.ArrayList;
public class WildcardDemo {
public static double sumOfList(List<? extends Number> list) {
double sum = 0;
for (Number n : list) {
sum += n.doubleValue();
}
return sum;
}
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
List<Double> doubleList = new ArrayList<>();
doubleList.add(1.5);
doubleList.add(2.5);
System.out.println(sumOfList(intList)); // 输出 3.0
System.out.println(sumOfList(doubleList)); // 输出 4.0
}
}


















