Junior — Middle
What data structure is used to implement a dynamic array similar to ArrayList?
sobes.tech AI
Answer from AI
A dynamic array similar to ArrayList in Java is implemented based on a regular array. The main idea is that when the current size of the array is reached, a new array with increased capacity (usually 1.5 to 2 times larger) is allocated, and all elements are copied into it.
This allows efficient addition of elements without frequent memory allocation, while maintaining quick access by index.
An example of simplified logic:
class SimpleArrayList<E> {
private Object[] data;
private int size = 0;
public SimpleArrayList() {
data = new Object[10];
}
public void add(E element) {
if (size == data.length) {
Object[] newData = new Object[data.length * 2];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
data[size++] = element;
}
public E get(int index) {
if (index >= size || index < 0) throw new IndexOutOfBoundsException();
return (E) data[index];
}
}