打印出任何数组的元素

时间:2011-12-11 18:07:43

标签: java arrays

在Java中是否有办法获得一个采用数组的方法 - 这里是重要部分 - 原始或非原始,并打印出其元素?我尝试了很多东西,包括泛型,但我似乎无法解决其中一些数组可能具有原始值的事实。

这是我到目前为止所拥有的,虽然它没有用,因为它没有编译:

    public static void dumpArray(Object a)
{
    for(int i = 0; i < a.length ; i++)
    {
        System.out.println(a[i]);
    }
}

这考虑到任何数组都是对象的子类型。

4 个答案:

答案 0 :(得分:10)

您可以使用Arrays.toString

它只是对每种基本类型的数组都有重载,而对Object[]还有一个重载。

static String toString(boolean[] a)
          Returns a string representation of the contents of the specified array.
static String toString(byte[] a)
          Returns a string representation of the contents of the specified array.
static String toString(char[] a)
          Returns a string representation of the contents of the specified array.
static String toString(double[] a)
          Returns a string representation of the contents of the specified array.
static String toString(float[] a)
          Returns a string representation of the contents of the specified array.
static String toString(int[] a)
          Returns a string representation of the contents of the specified array.
static String toString(long[] a)
          Returns a string representation of the contents of the specified array.
static String toString(Object[] a)
          Returns a string representation of the contents of the specified array.
static String toString(short[] a)
          Returns a string representation of the contents of the specified array.

如果你真的需要它是单个方法而不是重载集合那么你必须有一个Object类型的参数并使用反射来查看实际的内容type是然后调用适当的重载。

public static String toString(Object a) throws
    InvocationTargetException,
    NoSuchMethodException,
    IllegalAccessException
{
    Class clazz = Object[].class.isAssignableFrom(a.getClass())
         ? Object[].class : a.getClass();
    Method method = Arrays.class.getMethod("toString", new Class[] { clazz } );
    return (String)method.invoke(null, new Object[] { a });
}

查看在线工作:ideone

答案 1 :(得分:1)

public static void dumpArray(Object[] a)
{
    for(int i = 0; i < a.length ; i++)
    {
        System.out.println(a[i]);
    }
}

您只需更改参数,使其成为数组。 System.out.println(Object o)方法打印出o.toString(),在数字的情况下是与该数字对应的String。

例如,您可以使用不同的循环将int []转换为Integer []。

答案 2 :(得分:1)

是的,可以使用java.lang.reflect.Array完成。以下是代码段:

private static void printArray(Object array) {
    if(!array.getClass().isArray()) {
        throw new IllegalArgumentException();
    }
    int n = Array.getLength(array);
    for (int i = 0;  i < n;  i++) {
        System.out.println(Array.get(array, i));
    }
}

这就是如何调用它的例子:

    printArray(new int[] {1, 2, 3});
    printArray(new String[] {"aaa", "bbb"});

但这是一种不良做法&#34;。看一下Arrays.toString()的实现,他们为Object[]实现了一个版本,并为每个基本类型实现了特殊版本,尽管所有版本几乎相同。

所以,如果你真的想要使用我发布的解决方案,请好好想想。

答案 3 :(得分:0)

我认为这再一次证明了忽略类库中的某些东西是多么容易。

不要使用自己的代码,只需使用Arrays.deepToString()即可。

相关问题