java如何使用泛型
泛型的基本概念
泛型(Generics)是 Java 5 引入的特性,允许在类、接口或方法中使用类型参数,从而增强代码的类型安全性和复用性。泛型的核心目的是在编译时检查类型,避免运行时类型转换错误。
泛型类
泛型类通过类型参数定义,可以在实例化时指定具体类型。

public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
// 使用示例
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello");
String value = stringBox.getContent(); // 无需强制类型转换
泛型方法
泛型方法可以在非泛型类中定义,方法声明时指定类型参数。
public class Util {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
}
}
// 使用示例
Integer[] intArray = {1, 2, 3};
Util.<Integer>printArray(intArray); // 显式指定类型
Util.printArray(intArray); // 类型推断
泛型接口
泛型接口与泛型类类似,通过类型参数定义。

public interface Pair<K, V> {
K getKey();
V getValue();
}
// 实现泛型接口
public class OrderedPair<K, V> implements Pair<K, V> {
private K key;
private V value;
public OrderedPair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() { return key; }
@Override
public V getValue() { return value; }
}
// 使用示例
Pair<String, Integer> pair = new OrderedPair<>("Age", 25);
类型通配符
通配符(?)用于增强泛型的灵活性,支持未知类型的处理。
<?>:无限制通配符,表示任意类型。<? extends T>:上界通配符,表示T或其子类。<? super T>:下界通配符,表示T或其父类。
public static void printList(List<?> list) {
for (Object elem : list) {
System.out.print(elem + " ");
}
}
// 使用示例
List<Integer> intList = Arrays.asList(1, 2, 3);
printList(intList); // 支持任意类型
泛型限制
- 类型擦除:泛型信息在编译后被擦除,运行时无法获取具体类型。
- 不能实例化类型参数:
new T()是非法的。 - 不能用于静态上下文:静态变量或方法不能使用类的类型参数。
实际应用示例
通过泛型实现一个通用的缓存类:
public class Cache<T> {
private Map<String, T> cacheMap = new HashMap<>();
public void put(String key, T value) {
cacheMap.put(key, value);
}
public T get(String key) {
return cacheMap.get(key);
}
}
// 使用示例
Cache<Integer> intCache = new Cache<>();
intCache.put("count", 100);
int value = intCache.get("count");
最佳实践
- 优先使用泛型集合:如
List<String>而非原生List。 - 避免原生类型:原生类型(如
List)会失去类型安全检查。 - 合理使用通配符:在需要灵活处理类型时选择适当的通配符。
通过泛型,Java 实现了类型安全的代码复用,减少了运行时错误,是现代 Java 开发的核心特性之一。






