1

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("[");
    }

}
10
  • for your Q2) int is primitive while String is not and since every class in java is child of Object class implicitly ie every class by default extends Object class directly(or indirectly like in multi level inheritance) Commented Sep 15, 2018 at 10:02
  • Correct but Object obj = (int)1; is also correct Commented Sep 15, 2018 at 10:04
  • System.out.println(obj instanceof Integer); //prints true Commented Sep 15, 2018 at 10:06
  • 1
    docs.oracle.com/javase/tutorial/java/data/autoboxing.html Commented Sep 15, 2018 at 10:09
  • 1
    int[] cannot be implicitly casted to Object[] because int is not a sub-type of Object, but int[][] can because int[] can is a sub-type of Object. If you want to make your recPrintArray work with int[], you need to use the java.lang.reflect.Array class. Commented Sep 15, 2018 at 10:44

2 Answers 2

2

To answer your question, we need to introduce the concept of autoboxing first. Primitive types have their class matches. int has Integer, double has Double and so on. When a primitive type needs to be handled as an Object, the compiler will automatically convert the primitive into an instance of its wrapper class. Since you have an array of Objects, your primitive values are needed as Objects, so autoboxing will happen. If you want this to happen in a generic way, then you need to just check whether you have an array and if not, print the Object by calling its toString method.

As for your second question, you cannot convert a primitive array to an array of Objects, because your array was allocated for primitive types, not for Objects, but you can upcast a String array to an Object array, because all Strings are Objects.

Sign up to request clarification or add additional context in comments.

1 Comment

don't mention it :) it was a small one.
0

since in java multidimensional arrays are array of array and array is an object. so if i recursively iterate on any array references in the last i will get only one dimensional array which i can type cast explicitly in the type supplied by using getClass().getName()

package learning;
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 integerAr[][] = {{1},{2}};
        //byte byteAr[][] = {{1},{2}};
        //int[] intAr = (int[])byteAr;
        recPrintArray(ar);
    }

    public static void recPrintArray(Object ar) {
        recPrintArray(ar,getDimensions(ar));
    }

    public static void recPrintArray(Object ar,int noOfDimension) {
        for (Object obj:(Object[]) ar) {
            if (noOfDimension > 1)
                recPrintArray(obj, noOfDimension - 1);
            else {
                String dataType = obj.getClass().getName();
                switch (dataType) {
                case "[B":
                    printAll((byte[]) obj);
                    break;
                case "[S":
                    printAll((short[]) obj);
                    break;
                case "[I":
                    printAll((int[]) obj);
                    break;
                case "[J":
                    printAll((long[]) obj);
                    break;
                case "[F":
                    printAll((float[]) obj);
                    break;
                case "[D":
                    printAll((double[]) obj);
                    break;
                case "[Z":
                    printAll((boolean[]) obj);
                    break;
                case "[C":
                    printAll((char[]) obj);
                default:
                    printAll((Object[]) obj);
                }
                //System.out.print("> " + obj + " ");
            }
        }
    }

    public static void printAll(byte[] ar) {
        for (byte val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(short[] ar) {
        for (short val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(int[] ar) {
        for (int val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(long[] ar) {
        for (long val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(float[] ar) {
        for (float val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(double[] ar) {
        for (double val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(char[] ar) {
        for (char val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(boolean[] ar) {
        for (boolean val: ar)
            System.out.print(">" + val + " ");
    }

    public static void printAll(Object[] ar) {
        for (Object val: ar)
            System.out.print(">" + val + " ");
    }
    /*return the number of dimension of an array
     * takes any reference type as argument
     * using the Object class getClass() and Class getName() methods 
     */
    public static int getDimensions(Object intAr) {
        return intAr.getClass().getName().lastIndexOf("[");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.