Generic Methods:- The Below code will helps you to implement Generic Method using the Generic Programming in Java. The generic methods enable us to specify, with a single method declaration and use with different data types. we can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method.
In below code we have define the print() method as Generic Method and Use with both Integer and String Array to print the values of both arrays.
package com.util;
public class Gen {
public static <T> void print(T[] arr)
{
for(T t:arr)
{
System.out.println("Val : "+t);
}
}
public static void main(String[] args) {
Integer[] elements={1,2,3,4,5,6};
String[] names={"Akki","Manish","Sandeep","Ravinder"};
Gen.print(elements);
Gen.print(names);
}
}
0 Comment(s)