Junior — Middle
What steps are taken to add a new element to the ArrayList structure?
sobes.tech AI
Answer from AI
When adding a new element to an ArrayList, the following steps are performed:
- It checks whether the current internal array (usually Object[]) has enough space to store the new element.
- If there is not enough space, a new array with an increased size (usually 50% larger or 1.5 times bigger) is created, and all elements are copied into it.
- The new element is placed in the first free position of the internal array.
- The list size counter (size) is incremented.
Here's an example of how an element is added:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // check and expand array
elementData[size++] = e; // add element and increase size
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); // increase by 50%
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
elementData = Arrays.copyOf(elementData, newCapacity);
}