简体   繁体   中英

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 Integer[] , 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));
    }

您不能将原始数组传递给printArray()方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM