Why is an ArrayList of ArrayLists not multidimensional?
For the same reason the shopping bag I put all my spare shopping bags into is not a multidimensional shopping bag.
If I put a nut in one bag then put that bag in another bag, I have to perform two operations to get the nut.
If I instead put the nut in a two dimensional component tray, I can perform one operation to access it using two indices:
source
Similarly, there is a fundamental difference between a list of lists ( or array of arrays ) and a true two dimensional array - a single operation taking two indices is used to access the elements in a two dimensional array, two operations each taking one index are used to access the elements in a list of lists.
An ArrayList has a single index, so it has a rank of 1. A two dimensional array has two indices, its rank is 2.
note: by 'two dimensional array' I am not referring to a Java array of (references to) arrays, but a two dimensional array as found in other languages such as FORTRAN. Java does not have multidimensional arrays. If your interviewer was specifically referring to Java 'arrays of arrays' then I would disagree with them, as Java's int[][]
defines an array of references to arrays of integers, and that requires two dereferencing operations to access the elements. An array of arrays in C for example supports access with a single dereferencing operation so is closer to the multidimensional case.
Cay S. Horstmann has stated within his book Core Java for the impatient:
There are no two-dimensional array lists in Java, but you can declare a variable of type
ArrayList<ArrayList<Integer>>
and build up the rows yourself.
due to the fact that ArrayList
s can expand and shrink and become jagged rather than multi-dimensional, one could say it is not a two-dimensional array, multi-dimensional meaning fixed rows and columns, hence why I have also stated within the comments Java doesn't have true multi-dimensional arrays but this is outside the scope of your question.
if you're curious as to why I said Java doesn't have true multi-dimensional arrays have a read at the differences between a multidimensional array and an array of arrays in C#?
Just to make my answer clearer regarding whether Java has true multi-dimensional arrays or not, I did not say java doesn't have multi-dimensional arrays, I said Java doesn't have true multi-dimensional arrays and as expect the JLS has stated:
A multidimensional array need not have arrays of the same length at each level.