java泛型方法

2022-11-01  本文已影响0人  arkliu

泛型方法语法

修饰符 <T,E,K....>返回值类型  方法名(形参列表) {
    方法体..
}
public <T> T getSum(T a, T b) {
    return a+b;
}

\color{red}{泛型方法的类型,即使和泛型类声明相同,也可以有不同类型},看下面栗子:

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");
上一篇 下一篇

猜你喜欢

热点阅读