In java Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.
In Java, the way arrays and ArrayList
store their elements differs significantly, particularly in terms of memory allocation and management.
Contiguous Memory Allocation:
Fixed Size:
Dynamic Array:
ArrayList
is part of the Java Collections Framework and is implemented as a resizable array. It does not store its elements in a contiguous block of memory in the same way that a traditional array does.ArrayList
maintains an array to hold its elements, but this array can grow or shrink as needed. When the ArrayList
exceeds its current capacity, it creates a new, larger array and copies the elements from the old array to the new one.Non-Contiguous Memory:
ArrayList
are stored in an array, the array itself may not be contiguous in the same sense as a traditional array. This is because the ArrayList
can change its size dynamically, and the underlying array may be reallocated to accommodate new elements.ArrayList
provides methods to add, remove, and manipulate elements, which may involve creating new arrays and copying elements, leading to non-contiguous memory usage over time.Wrapper Objects:
ArrayList
can only store objects, not primitive types directly. When you store primitive types (like int
, char
, etc.) in an ArrayList
, they are automatically converted to their corresponding wrapper classes (like Integer
, Character
, etc.). This adds an additional layer of abstraction and can affect memory usage.