Generic method to print arrays in java

Tags: ,



I am trying to write a generic method printAll which prints an array of integer or character. Here’s the code:

public static void main(String[] args) {
    char cArray[] = {'a','b','c','d'};
    int iArray[] = {1,2,3,4};
    printAll(iArray);    // Error at this line--refer below the code

}

public static <T> void printAll(T[] t){
   for(T x:t) {
        System.out.println(x);
    }

}

Error: Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – Erroneous tree type: <.any>

Answer

printAll(T[] t) will not accept primitive type arrays. You need to pass arrays of the respective wrapper types:

Character cArray[] = {'a','b','c','d'};
Integer iArray[] = {1,2,3,4};

But, you don’t need to frame your own method. Just use the already existing – Arrays.toString() method, which is overloaded for different types of primitive arrays, and Object[] array.



Source: stackoverflow