0

When we write -

ArrayList al=new ArrayList(10);

Sometimes write an array like -
RefVar = new dataType[10];

What is happening in memory? whether the memory is located in continuous order or scattered order?

2 Answers 2

3

In principle, the Java language - neither the language spec nor the VM spec - doesn't mention how objects and arrays are to be implemented and does not guarantee consecutive memory allocation.

In practice, though, arrays are consecutive (only in their first dimension!), and ArrayList is implemented using an array, therefore the item references inside it are consecutive. Although the implementation of ArrayList includes other fields which are separate from the actual array.

If you add an element to an ArrayList whose internal array is already full, it will internally allocate a new, bigger array and copy all the existing element references to it. So even when that happens, the element references will still be consecutive (in practice).

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe mention something about growing the AL beyond the initiallly allocated size?
0

For arrays the elements will be in a continuous memory location.

And since ArrayList maintains index based system for its elements as it uses array data structure then its element also remain in a continuous memory location.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.