Print arrays in Java
•
Java
I'm writing a method to print every object it passes By calling object The toString () method works, but not for arrays I can use object getClass(). The isarray () method finds out if it is an array, but I don't know how to convert 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));
Solution
If you don't know the type, you can cast the object to object [] and print it like this (make sure it is indeed an array and can be converted to object []) If it is not an instance of object [], first create an object [], 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)); } } }
Test:
printAnyArray(new int[]{1,4,9,16,25}); printAnyArray(new String[]{"foo","bar","baz"});
OUTPUT:
[1,25] [foo,bar,baz]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码