Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an ArrayList of ArrayLists not multidimensional?

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?

like image 952
Lokesh Pandey Avatar asked May 09 '17 03:05

Lokesh Pandey


People also ask

Are ArrayLists multidimensional?

Overview. Creating a multidimensional ArrayList often comes up during programming. In many cases, there is a need to create a two-dimensional ArrayList or a three-dimensional ArrayList. In this tutorial, we'll discuss how to create a multidimensional ArrayList in Java.

Why is ArrayList single dimensional?

In Java, we have a Collection framework that provides functionality to store a group of objects. This is called a single-dimensional ArrayList where we can have only one element in a row.

Why Java does not support multi dimensional array?

This would be particularly difficult, because multidimensional arrays of different dimension counts would have an incompatible memory layout (because the size of their dimensions must be stored to enable bounds checking), and can therefore not be subtypes of each other. As a consequence, the methods of class java.

Can ArrayLists hold multiple data types?

It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types.


1 Answers

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.

like image 190
Ousmane D. Avatar answered Sep 24 '22 02:09

Ousmane D.