泛型方法定义
public class Util {
public static <T> void print(T value) {
System.out.println(value);
}
public static <T> T getFirst(T[] array) {
if (array == null || array.length == 0) {
return null;
}
return array[0];
}
}
String[] names = {"Alice", "Bob"};
String first = Util.getFirst(names);
泛型方法语法要点
修饰符后返回类型前声明<T>
类型参数T可以出现在方法各位置
编译器能自动推断类型
泛型方法重载
public class GenericOverload {
public static <T> void process(T input) {
System.out.println("单参数: " + input);
}
public static <T, V> void process(T first, V second) {
System.out.println("双参数: " + first + ", " + second);
}
}
小结
- 泛型方法在返回类型前声明<T>
- 静态方法可以使用泛型独立于类
- 编译器自动推断类型参数
- 泛型方法支持多类型参数