Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: are 1-d arrays always contiguous in memory?

Tags:

java

arrays

Many books/articles I've read on this topic, as well as a small program I wrote using 'Unsafe', indicate that 1-d arrays in Java are always contiguous in memory. So is it dictated by JLS or is it an implementation convention? The question is asked to confirm this indication.

like image 265
shrini1000 Avatar asked Apr 19 '12 09:04

shrini1000


People also ask

Are arrays contiguous in memory Java?

Arrays in Java, conceptually, are no different than in other programming languages. Arrays are contiguous memory locations storing only one type of item in a sequence.

Are all arrays contiguous in memory?

So array elements are contiguous in memory and therefore do not require any metadata. And linked list nodes are non-contiguous in memory thereby requiring metadata in the form of the location of the next node.

Why array is not continuous in Java?

The Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated. As all arrays are stored in heap and heap might be not continuous, it follows that arrays also might be not continuous.

Does an array occupies a contiguous block in memory?

If an array is 3D or multidimensional array, then the method of allocating memory is either row major or column major order. Whichever is the method, memory allocated for the whole array is contiguous and its elements will occupy them in the order we choose – row major or column major.


1 Answers

No, the JVM specification does not have any such guarantees: http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#16446

In practice it is probably the case but you also have no guarantee about the word size.

Unsafe is not a standard Java class, so if your program uses this, then it is not portable anyway...

like image 196
Mathias Schwarz Avatar answered Sep 17 '22 18:09

Mathias Schwarz