Java - Create generic method to output array


The following code creates a generic method.

E is used as a parameter. It is used to make the code more robust.

The task of printArray is to print both intArray and stringArray.

The procedure is same but both of them are of different datatypes.

We used Generics to implement the same method for both datatypes.


public class Main {

    static <E> void printArray(E[] array){
        for(E element : array){
        }// w ww. j  av  a 2 s  .  co m
    public static void main(String args[]){
        Integer[] intArray = { 1, 2, 3 };
        String[] stringArray = { "Hello", "World" };
        printArray( intArray  );
        printArray( stringArray );

Related Topic