Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array in java virtually sequential memory data structure? or physically sequential?

I try to find what is difference between primitive java 'array' and 'List' data structure (like ArrayList), and find articles or Q&A like this (Difference between List and Array). Many articles including that link point that java primitive 'array' is 'sequential memory'. In this point, what is sequential exactly? is this really sequential in physical memory? or sequential in virtual memory? My guess is sequential in virtual memory, because OS assigns physical memory in general and application(JVM) doesn't care about specific memory allocation. But I do not know exact answer.

like image 527
Stephen Choi Avatar asked Aug 25 '26 19:08

Stephen Choi


1 Answers

A Java array is sequential in virtual memory not necessarily in physical memory.

A user-space application (such as a JVM) has no say over whether the physical pages that make up its virtual address space are contiguous in memory. And in fact, it has no way of even knowing this in typical modern operating systems. This is all hidden from a user-space application by the machine's virtual memory hardware and (user-space) instruction set architecture.


Looking at the JVM spec is not going to be instructive on the physical memory issue. It is simply not relevant / out of scope.

The JVM spec doesn't mandate that arrays are contiguous in virtual memory. However, (hypothetical) array implementations that involved non-contiguous virtual memory would lead to expensive array operations, so you are unlikely to find a mainstream JVM that does this.

References:

  • JVM Spec 2.7 says:

    "The Java Virtual Machine does not mandate any particular internal structure for objects."

    Other parts of the spec imply that "objects" refers here to BOTH instances of classes AND arrays.

  • JVM Spec 2.4 talks about arrays, but it doesn't mention how they are represented in memory.


The difference between arrays and ArrayLists are at a higher level. Arrays have a fixed size. ArrayLists have a variable size. But under the hood, an ArrayList is implemented using a (single) array ... which can be reallocated (i.e. replaced) if the list grows too big.

like image 185
Stephen C Avatar answered Aug 28 '26 07:08

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!