Primitive types like int
are not Objects while an array is an Object-- you can assign any array to an Object reference
Object o = new int[]{7, 9, 8};
new int[][]
is an array of objects and thus can be assigned to Object[]
. You may want to write a utility method like this to do what you want:
public static String arrayToString(Object o) {
if(o instanceof Object[]) {
return Arrays.deepToString((Object[]) o);
}
else if(o instanceof long[]) {
return Arrays.toString((long[]) o);
}
else if(o instanceof int[]) {
return Arrays.toString((int[]) o);
}
else if(o instanceof short[]) {
return Arrays.toString((short[]) o);
}
else if(o instanceof byte[]) {
return Arrays.toString((byte[]) o);
}
else if(o instanceof float[]) {
return Arrays.toString((float[]) o);
}
else if(o instanceof double[]) {
return Arrays.toString((double[]) o);
}
else if(o instanceof boolean[]) {
return Arrays.toString((boolean[]) o);
}
throw new IllegalArgumentException("input is not an array");
}
Example:
Object intArray = new int[]{7, 9, 8};
Object[] intintArray = new int[][]{{1, 2, 3}, {6, 5, 4}};
Object[] intintintArray = new int[][][]{{{1, 2, 3}, {6, 5, 4}},
{{1, 2, 3}, {6, 5, 4}}};
System.out.println(arrayToString(intArray));
System.out.println(arrayToString(intintArray));
System.out.println(arrayToString(intintintArray));
Output:
[7, 9, 8]
[[1, 2, 3], [6, 5, 4]]
[[[1, 2, 3], [6, 5, 4]], [[1, 2, 3], [6, 5, 4]]]