- 泛型类,是在实例化类的时候指明泛型类型
- 泛型方法是在调用方法的时候指明泛型的具体类型
- 只有声明了<T>的方法才是泛型方法。泛型类中使用了泛型的成员方法并不是泛型方法
泛型方法语法
修饰符 <T,E,K....>返回值类型 方法名(形参列表) {
方法体..
}
public <T> T getSum(T a, T b) {
return a+b;
}
,看下面栗子:
public class ProductGet <T>{
private T product; //奖品
Random random = new Random();
List<T>list = new ArrayList<>(); // 奖品池
// 该方法不是泛型方法
public T addPro(T t) {
return t;
}
//该方法是泛型方法
public <T> T getPro(ArrayList<T> arr) {
return arr.get(random.nextInt(arr.size()));
}
public static void main(String[] args) {
//泛型类指定为String
ProductGet<String> strProGet = new ProductGet<>();
//泛型方法指定为Integer
ArrayList<Integer>intlist = new ArrayList<>();
intlist.add(300);
intlist.add(400);
intlist.add(500);
int intPro = strProGet.getPro(intlist);
System.out.println("获得了:"+intPro);
}
}
泛型方法可变参数,和多个泛型参数
public class ProductGet <T>{
private T product; //奖品
// 可变参数泛型方法
public static <T> void printT(T ... params) {
for (int i = 0; i < params.length; i++) {
System.out.println(params[i]);
}
}
// 多个泛型类型的泛型方法
public static <T,E,K> void printType(T t, E e, K k) {
System.out.println("t:"+t.getClass()+" e:"+e.getClass()+" k:"+k.getClass());
}
}
ProductGet.printT("hello", "world", "你好", "世界");
ProductGet.printT(22, 33,44,55);
ProductGet.printType(11, 22.5, "hello");






网友评论