2

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?

Mehdi Charife
  • 722
  • 1
  • 7
  • 22
0day
  • 103
  • 1
  • 10
  • 1
    Why do you care? If you must know, read this: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java?av=f GrepCode is your friend for this type of question. – Jim Garrison Jan 30 '17 at 05:35
  • 1
    Well, `ArrayList` is based on Java arrays. And Java arrays are not guaranteed to be contiguous in memory. But why does it matter anyway. – xiaofeng.li Jan 30 '17 at 05:37
  • 1
    I would have thought that the answer would be OS specific anyway – Scary Wombat Jan 30 '17 at 05:38
  • 2
    @JimGarrison Surely a thorough mental model is always a good thing? Or, simple curiosity? Knowing the answer can help to get a thorough grasp on, for instance, the differences between simple Arrays and ArrayLists in memory. – andydavies Oct 05 '17 at 10:37

1 Answers1

4

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...

Adam
  • 35,919
  • 9
  • 100
  • 137
  • The reason I was just searching for this is because I was reading of advantages of various data structures over others, and one of the advantages of arrays is contiguous memory allocation. I am assuming ArrayLists do not have that advantage from your answer.. – adinutzyc21 Jan 31 '17 at 05:05
  • In terms of relative cost yes Arrays will be almost certainly be quicker in Java than say a linked list. However Java does make guarantees about how structures map onto underlying memory in the same way say C++ does – Adam Jan 31 '17 at 07:18