Generic Method

  • If you are going to use generic in a method then you need to specify all the generics used in that method inside a diamond operator, this diamond operator will come right after the access modifier of the method.
  • You need to mention the type used inside the method after the class name.

Example :

class GenericMethodDemo{
	public <T1,T2> String genericToString(T1 t1, T2 t2){
		return t1.toString()+" -- "+t2.toString();
	}
}
  • By using generic method the reuse-ability of the method increases
  • Method becomes type safe, instead of using Object datatype and casting to our need at runtime can runtime exceptions, instead by using generic we know before hand what datatype is going to be referred in future.
  • And thus overhead of casting the object is also removed.
  • Array of Generic type can also be created using Generic, example below

public class GenericArray {
	public static <T> void printArray(T[] array) {
		System.out.println();
		for(T input : array) {
			System.out.print(input+" --> ");
		}
	}
	public static void main(String[] args) {
		Integer[] arr1 = new Integer[]{10,20,30};
		String[] arr2 = new String[]{"Tyson","Justin","Martin"};
		printArray(arr1);
		printArray(arr2);
	}
}

Leave a Comment