Java generic methods

Generic methods have no requirements for their classes. That is, the class in which a generic method resides may or may not be a generic class.

Rules for Java generics generic methods:

  • A generic method declaration simply lists the generic parameters before the return value.
  • Each type parameter section contains one or more type parameters, separated by commas. Type parameters (also known as type variables) are identifiers that specify the name of a generic type.
  • Type parameters can be used to declare return types and serve as placeholders for parameter types passed to generic methods, which are called actual type parameters.
  • Declare a generic method body as any other method. Note that type parameters can only represent reference types, not primitive types (such as int, double, and char).
public class GenericMethods {

    public static void main(String[] args) {
        Integer[] intArray = {1.2.3.4.5};
        String[] strArray = {"a"."b"."c"."d"."e"};
        printArray(intArray);public class GenericMethods {

        public static void main(String[] args) {
          Integer[] intArray = {1.2.3.4.5};
          String[] strArray = {"a"."b"."c"."d"."e"};
          printArray(intArray);
          printArray(strArray);

          ArrayList<String> list = new ArrayList<>();
          list.add("xiaoMing");
          list.add("xiaoHong");
          list.add("xiaoGou");
          System.out.println(list);

          printGeneric("");
          printGeneric(1);
          printGeneric(1.0);
          printGeneric(2.0 F);
          printGeneric('c');
          printGeneric(new GenericMethods());


        }

        // Generic methods
        public static <E> void printArray(E[] eArray){
          for(E e : eArray) { System.out.print(e); }}public static <T> void printGeneric(T t){
          System.out.println(t.getClass().getName());
        }
      }
        printArray(strArray);

        ArrayList<String> list = new ArrayList<>();
        list.add("xiaoMing");
        list.add("xiaoHong");
        list.add("xiaoGou");
        System.out.println(list);


    }

    // Generic methods
    public static <E> void printArray(E[] eArray){
        for(E e : eArray) { System.out.println(e); }}}Copy the code

Although both the above class and its internal methods can be parameterized, only the generic methods in the above example have type parameters. This is indicated by the type parameter list before the return value type of the method.

Output result:

12345abcde[xiaoMing, xiaoHong, xiaoGou]
java.lang.String
java.lang.Integer
java.lang.Double
java.lang.Float
java.lang.Character
cn.ling.generic.GenericMethods
Copy the code