zoukankan      html  css  js  c++  java
  • Java中泛型方法的定义

    1. 泛型方法的概念

    方法的参数类型是泛型,而不是具体的参数。
    注意:是方法的参数是泛型,而不是方法的返回值。

    2. 泛型方法的定义格式

    [访问权限] <泛型> 返回值类型 方法名([泛型标识 参数名称]){方法体;}

    3. 泛型方法实例

    public <T2> void printArray(T2[] arr){
          for (int i = 0; i < arr.length; i++) {
                System.out.println(arr[i]);
          }
    }
    

    以上方法就是泛型方法,方法的参数是一个数组,但是这个数组存放的数据类型不是具体的,而是一个泛型。另外,因为这个T2泛型是我们自己定义的,不是Java官方的。
    所以为了表示T2也是一种泛型标识,需要在方法的前面也需要添加泛型,用于告诉编译器T2表示泛型。

    4. 注意事项

    public class Person<T> {
          private String name;
          private int age;
          private T gender;
          ...
          public T getGender() {
                return gender;
          }
    }
    

    以上的getGender并不是泛型方法,因为该方法没有泛型参数,只是返回值是泛型。并且getGender方法不能被static修饰,因为被static修饰的方法不需要new对象就可以访问。而T泛型的具体类型是需要new对象的时候才指定的,两者是矛盾的。
    总结 :方法的返回值是泛型的话,该方法不能被static修饰。

    如果需要使用static修饰,那么也需要将该静态方法设置成泛型方法,实例如下:

    public class Person<T> {
          private String name;
          private int age;
          private T gender;
          ...
          public static <T> void getGender(T gender) {
                System.out.println(gender);
          }
    }
    

    总结:如果静态方法要使用泛型的话,必须将静态方法也定义成泛型方法 。

  • 相关阅读:
    faster with MyISAM tables than with InnoDB or NDB tables
    w-BIG TABLE 1-toSMALLtable @-toMEMORY
    Indexing and Hashing
    MEMORY Storage Engine MEMORY Tables TEMPORARY TABLE max_heap_table_size
    controlling the variance of request response times and not just worrying about maximizing queries per second
    Variance
    Population Mean
    12.162s 1805.867s
    situations where MyISAM will be faster than InnoDB
    1920.154s 0.309s 30817
  • 原文地址:https://www.cnblogs.com/kyle-blog/p/14165121.html
Copyright © 2011-2022 走看看