Wednesday, May 18, 2011

Visualizing 2D arrays : How java implements multidimensional arrays ?

A two dimensional array is implemented as an array of one dimensional arrays. This is called "array of arrays" approach.

2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an array, a, with two rows and four columns.

int[][] a = new int[2][4];  // Two rows and four columns.

Two-dimensional arrays are usually visualized as a matrix, with rows and columns. This diagram shows the array a with its corresponding subscripts.

This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual row arrays, and a two one-dimensional arrays of 4 elements to represent the contents of the rows.

Common approach to implement multidimensional arrays

There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Some languages, like Java, build multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. C++ supports both styles.

No comments:

Post a Comment