Why is an ArrayList of ArrayLists not multidimensional?

Lokesh :

I recently appeared for an interview in which the interviewer asked me a question regarding Arrays and ArrayList.

He asked me if an array of arrays can be multidimensional, then why is an ArrayList of ArrayList's not multidimensional?

For example:

// Multidimensional
int[][] array = new int[m][n]; 

// Not multidimensional
ArrayList<ArrayList<Integer>> seq = new ArrayList<ArrayList<Integer>>(); 

Can anyone help me to understand this?

Ousmane D. :

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 ArrayLists 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=425434&siteId=1