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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With