通用的方法来打印所有元素的数组

通用的方法来打印所有元素的数组

问题描述:

我想那会循环任何类型的数组,并打印出来,我写了下面的方法:

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

但这个只适用于类数组,如果我有一个的的char [] 代替字符[] INT [] 代替整数[] ,或者是有没有办法之前投他们手?谢谢

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(阵列)应该做的。


  • 公郎也有 - ArrayUtils.toString(阵列)(但preFER JDK的一个)

  • 公郎允许自定义分隔符 - StringUtils.join(数组,',')

  • 番石榴还允许隔板,并具有跳过空值的选项: Joiner.on('')。skipNulls()。加入(阵列)

  • 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)

所有这些返回字符串,你可以再的System.out.println(..) logger.debug(..)。请注意,这些会给你有意义的投入,如果数组的元素已经实施的toString()以有意义的方式。

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.