通用的方法来打印所有元素的数组 [英] generic method to print all elements in an array

查看:143
本文介绍了通用的方法来打印所有元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于通用的方法来打印所有元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆