1
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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
ihsanaji
  • 29
  • 2
  • 7
    There isn't a convenient way or inbuild method, you have to do it via nested for loops. – HopefullyHelpful Jun 08 '16 at 23:29
  • Yup. You have to loop through it in a nested loop and use something like for (Integer[] integers : documents) {for (Integer integer : integers) {}} as your loop. Inside your nested loop you'll then convert the Integer to an int and assign it. – Dale Jun 08 '16 at 23:33
  • I'm curious... why you aren't using something like an ArrayList? – Dale Jun 08 '16 at 23:36
  • Reopen. Not a duplicate. I didn't see any answers pertaining to 2D arrays. – djechlin Jun 08 '16 at 23:43

1 Answers1

1

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;
}
Samuel
  • 16,923
  • 6
  • 62
  • 75