What are generic methods in Java?


Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method.

  • While defining a generic method you need to specify the type parameter within the angle brackets (< T >). This should be placed before the method's return type.

  • You can have multiple type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

  • The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

Example1

 Live Demo

public class GenericMethod {
   <T>void sampleMethod(T[] array) {
      for(int i=0; i<array.length; i++) {
         System.out.println(array[i]);
      }
   }
   public static void main(String args[]) {
      GenericMethod obj = new GenericMethod();
      Integer intArray[] = {45, 26, 89, 96};
      obj.sampleMethod(intArray);
      String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
      obj.sampleMethod(stringArray);
   }
}

Output

45
26
89
96
Krishna
Raju
Seema
Geeta

Example2

 Live Demo

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class GenericMethodExample {
   public static <T> void arrayToCollection(T[] array, Collection<T> coll ) {
      for(int i=0; i<array.length; i++) {
         coll.add(array[i]);
      }
      System.out.println(coll);
   }
   public static void main(String args[]) {
      Integer [] intArray = {24, 56, 89, 75, 36};
      ArrayList<Integer> al1 = new ArrayList<Integer>();
      arrayToCollection(intArray, al1);
      String [] stringArray = {"Ramu", "Raju", "Rajesh", "Ravi", "Roshan"};
      ArrayList<String> al2 = new ArrayList<String>();
      arrayToCollection(stringArray, al2);
   }
}

Output

[24, 56, 89, 75, 36]
[Ramu, Raju, Rajesh, Ravi, Roshan]
raja
Published on 09-Sep-2019 11:22:25
Advertisements