I want a generic method to print all the elements of a multidimensional array. In the below code i am able to print all the elements of any multidimensional array which belongs to the parent Object class but not of any primitive types. Is it possible to print all elements of a multidimensional array of primitive type. One more doubt if int value can be hold in a Object type then why not int[] can be cast to Object[] but, String[] can be cast to Object[].
public class MultiDimension {
public static void main(String[] args) {
//final String ar[][][] = {{{"1","2"},{"3","4","5"}},{{"6","7","8"}},{{"9","10"},{"11"},{"12","13","14","15"}}};//new String[1][3][2][2];
Integer intAr[][][][][][] = {{{{{{1},{2},{3}},{{4},{5},{6}}},{{{7}},{{8}}}}}};
recPrintArray(intAr);
}
public static void recPrintArray(Object ar) {
recPrintArray((Object[])ar,getDimensions(ar));
}
public static void recPrintArray(Object[] ar,int noODDimension) {
for (Object obj:(Object[]) ar) {
if (noODDimension > 0)
recPrintArray((Object[])obj, noODDimension - 1);
else {
System.out.print("> " + obj + " ");
}
}
}
/*return the number of dimension of an array
* takes any type as argument
* using the Object class getClass() and Class class getName() methods
*/
public static int getDimensions(Object intAr) {
return intAr.getClass().getName().lastIndexOf("[");
}
}
System.out.println(obj instanceof Integer); //prints trueint[]cannot be implicitly casted toObject[]becauseintis not a sub-type ofObject, butint[][]can becauseint[]can is a sub-type ofObject. If you want to make yourrecPrintArraywork withint[], you need to use thejava.lang.reflect.Arrayclass.