在 Java 中有没有一种方法可以有一个方法,它接受一个数组——这是重要的部分——原始的或非原始的,并打印出它的元素?我尝试了很多东西,包括泛型,但我似乎无法回避这样一个事实,即其中一些数组可能具有原始值。
这是我目前所拥有的,虽然它没有那么有用,因为它没有编译:
public static void dumpArray(Object a)
{
for(int i = 0; i < a.length ; i++)
{
System.out.println(a[i]);
}
}
这考虑到任何数组都是对象的子类型。
最佳答案
您可以使用 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
类型的参数并使用反射来查看实际类型是什么,然后调用适当的重载。
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
关于java - 打印出任何数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8466244/