What are the differences between multidimensional arrays
and array-of-arrays
?
Why Java supports arrays of arrays
, rather than multidimensional arrays
?
What are the differences between multidimensional arrays
and array-of-arrays
?
Why Java supports arrays of arrays
, rather than multidimensional arrays
?
Although your why question is probably unanswerable at this point (it would take one of the original creators of Java to answer it), you may note that a strong design principle of the original Java was simplicity. In that spirit all that Java supports is an array, which on its own gives you an array of arrays as just a special case: such an array whose component type is array.
About the only advantage of a true multidimensional array is the way its members are packed together, offering better cache locality. Such concerns were not high on the list of design priorities of original Java, although today they are getting a much greater share of the spotlight.
Refer to this topic for an in-depth review of pros and cons of multidimensional arrays.
Short answer: because the language was designed this way. But an array of arrays functions as a multidimensional arrays, so this is not really a limit on the language.
Probably the reason for this is that Java borrowed its array syntax from C and C++, and C and C++ multidimensional arrays are also accessed as though they are arrays of arrays. The difference is that in Java an array of arrays is an array of references to arrays (and thus the arrays in the array can have different lengths).