generic method to print all elements in an array

对着背影说爱祢 提交于 2019-12-06 17:25:13

问题


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 Integer[], or is there a way to cast them before hand? Thanks


回答1:


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.




回答2:


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)



回答3:


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));
    }



回答4:


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



来源:https://stackoverflow.com/questions/5861926/generic-method-to-print-all-elements-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!