When we use new ArrayList()
is memory contiguously allocated?
If we call list.add(e)
10 times, will all elements be contiguously stored in memory by add order, or will they be randomly stored in memory?
Firstly you need to understand how ArrayList works. It stores "references" or "pointers" to actual storage in an internal object array elementData
. This array of references may well be contiguous, but is JVM specific. The actual objects being added are stored on the heap, and almost certainly won't be contiguous, although this is JVM specific.
elementData[0] ===> object 1
elementData[1] ===> object 2
elementData[2] ===> object 3
...
Secondary, you mention calling add() multiple times... When ArrayList internal elementData is no longer big enough it resizes it to a bigger one, +50% IIRC, and copies all the references to the new elementData, the actual objects do not move.
Lastly contiguous memory is typically a concern of high-performance native applications. In Java memory is managed by the JVM and is borrowed from the underlying OS, in turn from the hardware, or even virtualized hardware.
© 2022 - 2024 — McMap. All rights reserved.
ArrayList
is based on Java arrays. And Java arrays are not guaranteed to be contiguous in memory. But why does it matter anyway. – Groundhog