I found this topic on a similar Stack Overflow thread.
In c++, when you make an array int[i][j] you get row major order, so iterating by row will give you caches which contain more useful data.
In java, there is no 2d array, but it still creates something similar enough in terms of caches. My question is, does it create the arrays of actual data in the size of row, or does it create the array of pointers in size of row?
Or, as the top answer on the similar Stack Over thread said, does it do something entirely different where int[5][8] would be an array of 5 pointers to arrays of any size that all add up to (5*8)?
It said java makes jagged arrays, and I can’t think of any good reason for this to be true.
I don’t know about the C++ behaviour, but it sounds like you’re expecting something in the Java behaviour which may very well not be the case. If you write:
then that’s equivalent to:
There are 6 separate arrays here. At any point, you could write:
It’s just an array of arrays – jagged by definition. There’s nothing to say it’ll stay rectangular forever, or even that all the elements of the “top-level” array will be non-null.
I’d expect the values to start off close to each other in memory, but there’s no guarantee that they’d stay that way.
If you really want to make sure you have a contiguous block of memory, you should use
int[] x = new int[40];instead.