ihsanaji ihsanaji - 6 months ago 13
Java Question

How do you convert a two dimensional array of a boxed type to a two dimensional array of the corresponding primitive type?

Integer[][] documents = { {1, 4, 3, 2, 3, 1, 4, 3, 2, 3, 1, 4, 3, 2, 3, 6},
{2, 2, 4, 2, 4, 2, 2, 2, 2, 4, 2, 2},
{1, 6, 5, 6, 0, 1, 6, 5, 6, 0, 1, 6, 5, 6, 0, 0},
{5, 6, 6, 2, 3, 3, 6, 5, 6, 2, 2, 6, 5, 6, 6, 6, 0},
{2, 2, 4, 4, 4, 4, 1, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 0},
{5, 4, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2}};
int[][] convertDocument = documents;


the compiler says incompatible types: Integer[][] cannot be converted to int[][]...
how to solve this?

Answer

You have to iterate over the list and convert each element into an int primitive. Arrays are special kinds of objects in Java, so int[][] and Integer[][] are completely unrelated to each other. It would be like trying to cast a Foo to a Bar. Java does support implicit casts from Integer to int however. That's called auto-boxing, and you can see it at work below at the line primitives[i][j] = documents[i][j] where a single Integer is implicitly cast to a primitive int.

int[][] convertToPrimitives(Integer[][] documents) {
    int[][] primitives = new int[documents.length][];
    for (int i=0;i<documents.length;i++) {
        primitives[i] = new int[documents[i].length];
        for (int j=0;j<documents[i].length;j++) {
            primitives[i][j] = documents[i][j];
        }
    }
    return primitives;
}