在 Java 中,泛型方法是指在方法声明时单独定义类型参数(<T> 等),不依赖类是否泛型。
修饰符 <类型参数> 返回类型 方法名(参数列表) {
// 方法体
}
关键点:
<T> 放在返回值前面<T, U>extends 限制类型public class Demo {
public static <T> void print(T t) {
System.out.println(t);
}
public static void main(String[] args) {
print("hello");
print(123);
}
}
✅ T 在调用时自动推断
public static <T> T getFirst(T[] array) {
return array[0];
}
调用:
String s = getFirst(new String[]{"a", "b"});
Integer i = getFirst(new Integer[]{1, 2});
public static <K, V> void show(K key, V value) {
System.out.println(key + " = " + value);
}
public static <T extends Number> double toDouble(T t) {
return t.doubleValue();
}
❌ 下面会编译错误:
toDouble("abc"); // String 不是 Number
class Box<T> {
T value;
}
class Util {
static <T> T get(T t) {
return t;
}
}
✅ 泛型方法不要求类本身是泛型
Collections.sort、Arrays.asList)如果你愿意,我可以给你:
? 的区别你想看哪一个?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。