用Java打印数组 [英] Print arrays in Java
问题描述
我正在编写一个方法来打印它传递的每个Object。通过为对象调用 Object.toString()
方法可以正常工作,但不适用于数组。我可以通过 Object.getClass()。isArray()
方法找出它是否是一个数组,但我不知道如何投射它。
I'm writing a method that prints every Object it get passed. This works fine by calling the Object.toString()
method for the object but doesn't works for arrays. I can find out whether it is an Array with the Object.getClass().isArray()
method, but I don't know how to cast it.
int[] a;
Integer[] b;
Object aObject = a;
Object bObject = b;
// this wouldn't work
System.out.println(Arrays.toString(aObject));
System.out.println(Arrays.toString(bObject));
推荐答案
如果您不知道可以投的类型对象 Object []
并打印出来(确定它确实是一个数组后可以转换为 Object []
)。如果它不是 Object []
的实例,则使用 reflection 创建 Object []
首先打印:
If you don't know the type you can cast the object to Object[]
and print it like this (after making sure it is indeed an array and can be cast to Object[]
). If it is not an instance of Object[]
then use reflection to create an Object[]
first and then print:
private void printAnyArray(Object aObject) {
if (aObject.getClass().isArray()) {
if (aObject instanceof Object[]) // can we cast to Object[]
System.out.println(Arrays.toString((Object[]) aObject));
else { // we can't cast to Object[] - case of primitive arrays
int length = Array.getLength(aObject);
Object[] objArr = new Object[length];
for (int i=0; i<length; i++)
objArr[i] = Array.get(aObject, i);
System.out.println(Arrays.toString(objArr));
}
}
}
测试:
printAnyArray(new int[]{1, 4, 9, 16, 25});
printAnyArray(new String[]{"foo", "bar", "baz"});
输出:
[1, 4, 9, 16, 25]
[foo, bar, baz]
这篇关于用Java打印数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!