开发者

generic method to print all elements in an array

I wanna a method that would loop any type array and print them, I have written the following:

public static <T> void printArray(T[] arr){
    for(T t: arr){
       System.out.print(t+" ");
    }
    System.out.println("");
}

but this one only works for class arrays, what if I have a char[] instead of a Character[], or a int[] instead of an Integ开发者_JAVA百科er[], or is there a way to cast them before hand? Thanks


java.util.Arrays.toString(array) should do.

  • commons-lang also have that - ArrayUtils.toString(array) (but prefer the JDK one)
  • commons-lang allows for custom separator - StringUtils.join(array, ',')
  • guava also allows a separator, and has the option to skip null values: Joiner.on(',').skipNulls().join(array)

All of these return a String, which you can then System.out.println(..) or logger.debug(..). Note that these will give you meaningful input if the elements of the array have implemented toString() in a meaningful way.

The last two options, alas, don't have support for primitive arrays, but are nice options to know.


You cant write a generic definition for primitive arrays. Instead, you can use method overloading and write a method for each primitive array type like this,

public static void printArray(int[] arr)
public static void printArray(short[] arr)
public static void printArray(long[] arr)
public static void printArray(double[] arr)
public static void printArray(float[] arr)
public static void printArray(char[] arr)
public static void printArray(byte[] arr)
public static void printArray(boolean[] arr)


private static void printArray(Object arr) {
        // TODO Auto-generated method stub
        String arrayClassName=arr.getClass().getSimpleName();
        if (arrayClassName.equals("int[]"))
            System.out.println(java.util.Arrays.toString((int[]) arr));
        if (arrayClassName.equals("char[]"))
            System.out.println(java.util.Arrays.toString((char[]) arr));
    }


You can't pass primitive arrays to the printArray() method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜