Object matrix = Array - what's wrong with an array reflection tutorial using the Oracle website as an example

I am trying to follow this guide to parsing an array on an Oracle website, which does not seem to work. Since this is Oracle's own documentation, I'm just wondering if I'm not doing something wrong:

Object matrix = Array.newInstance(int.class, 2); Object row0 = Array.newInstance(int.class, 2); Object row1 = Array.newInstance(int.class, 2); Array.setInt(row0, 0, 1); Array.setInt(row0, 1, 2); Array.setInt(row1, 0, 3); Array.setInt(row1, 1, 4); Array.set(matrix, 0, row0); // <- This throws IllegalArgumentException Array.set(matrix, 1, row1); 

Now I know that in Java 2d, arrays are basically just nested arrays, so theoretically this should work. Did I miss something?

Thanks!

+4
source share
1 answer

I assume the code is incorrect on oracle site

It should be

  Object matrix = Array.newInstance(int.class, 2, 2); 

Code

  Object matrix = Array.newInstance(int.class, 2); 

creates an array of size 2, but the array objects must be int.class.

Full code:

 import java.lang.reflect.Array; import static java.lang.System.out; public class CreateMatrix { public static void main(String... args) { Object matrix = Array.newInstance(int.class, 2, 2);//var arg was wrong in docs? Object row0 = Array.newInstance(int.class, 2); Object row1 = Array.newInstance(int.class, 2); Array.setInt(row0, 0, 1); Array.setInt(row0, 1, 2); Array.setInt(row1, 0, 3); Array.setInt(row1, 1, 4); Array.set(matrix, 0, row0); Array.set(matrix, 1, row1); for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) out.format("matrix[%d][%d] = %d%n", i, j, ((int[][]) matrix)[i][j]); } } 
+3
source

All Articles