Saturday, March 16, 2013

Multidimensional arrays and Java


There are no true multidimensional arrays in Java. This is Java 101. But why?

I always knew that Java's closest representation was arrays of arrays. This differs from true multidimensional arrays as the length of the second array is not bound. That is, an  M x N multidimensional array can be represented in Java but also, it might be jagged (that is, N is not the same for all M).


        int[][] array2D = new int[2][];

        array2D[0] = new int[] {1,2,3};
        array2D[1] = new int[] {1,2,3,4,5};

        // prints: [[1, 2, 3], [1, 2, 3, 4, 5]]
        System.out.println(Arrays.deepToString(array2D));

        assertEquals(3, array2D[0].length);
        assertEquals(5, array2D[1].length);

In a true multidimensional arrays, each row would have the same length.

This shouldn't be too surprising. But a silly bug this week also highlighted another aspect of why 2 (or more) dimensioned arrays are not true multidimensional arrays.


        int[][] original = new int[10][10];
        assertEquals(0, original[5][5]);
        int[][] copied = original.clone();

        // change element in the '1st dimension'
        copied[4] = new int[] {1, 2, 3, 4, 5};
        assertEquals(2, copied[4][1]);
        assertEquals(0, original[4][1]); // change not seen in the original

        // change element in the '2nd dimension'
        copied[5][5] = 100;
        assertEquals(100, copied[5][5]);
        assertEquals(0, original[5][5]); // fails. change *is* seen in the original

Cloning an array produces a deep copy of the first array but not the elements in it (the other "dimensions"). These other "dimensions" of the array are treated like any other object and are not deep copied. In this way, our "multidimensional" array is just like a 1-D array of any other type of object.

No comments:

Post a Comment