Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a 1D array of N elements need the same amount of memory as 2D[m][n], m*n=N

Tags:

java

arrays

Here's the question about memory allocation in Java.

Suppose I have an array of ints A[100] and another array of ints B[10][10]. Do they need the same amount of memory in Java or is it different? If the latter, what's the difference and how does it grow with N?

I'm talking here only about Ns that are power of 2 of a positive number, so we're talking here about square 2D arrays and their possible 1D representation.

like image 300
alekscooper1 Avatar asked Dec 25 '22 17:12

alekscooper1


1 Answers

Definitively, no.

In C/C++ a 2D-array allocates all memory for the 2D-array in "one chunk".

In Java, a 2D-array is an "array of arrays". One-dimensional arrays are allocated in one chunk, but the one-dimensional arrays may be scattered. Furthermore, the "outer" array (2nd dimension) needs heap memory as well, storing the references to the 1D-arrays.

So if one allocates a 2D-array of dimensions m (outer) and n (inner), Java will create one array of m elements and m arrays ofn elements each. The outer array just stores the references to the m inner arrays.

This page gives a nice explanation and visualization of multidimensional arrays in Java.

like image 177
Turing85 Avatar answered May 01 '23 08:05

Turing85