Article by: Manish Methani
Last Updated: October 23, 2021 at 8:04am IST
Suppose you have an integer array of 4 elements
Integer[] iray = {10,20,30,40};
And one character array of 4 characters
Character[] cray = {'c','o','d','z'}
Now if you want to print the elements in both of these arrays you have to write two different print methods. And Suppose in future there is also Float[] array and double[] array too. Then think you have to write a print method to display the elements of array four times.
So here, Generic Methods comes into existence. One method can handle different types . Thats why it is called as generic Type.
import java.util.*; public class JavaGenericMethods { public static void main(String[] args) { Integer[] iray = {10,20,30,40}; Character[] cray = {'c','o','d','z'}; Double[] dray = {10.2,12.3,14.6}; printElements(iray); printElements(cray); printElements(dray); } public static void printElements(Integer[] i) { for(Integer x: i ) { System.out.printf("%s ", x); } System.out.println(); } public static void printElements(Character[] c) { for(Character x: c ) { System.out.printf("%s ", x); } System.out.println(); } public static void printElements(Double[] i) { for(Double x: i ) { System.out.printf("%s ", x); } System.out.println(); } }
10 20 30 40 c o d z 10.2 12.3 14.6
import java.util.*; public class JavaGenericMethods { public static void main(String[] args) { Integer[] iray = {10,20,30,40}; Character[] cray = {'c','o','d','z'}; Double[] dray = {10.2,12.3,14.6}; printElements(iray); printElements(cray); printElements(dray); } public static void printElements(T[] i) { for(T x: i ) { System.out.printf("%s ", x); } System.out.println(); } }
10 20 30 40 c o d z 10.2 12.3 14.6