Junior — Middle
Can you explain the principle of operation of the ArrayList data structure?
sobes.tech AI
Answer from AI
ArrayList is a dynamic array in Java that automatically expands when elements are added. It uses a regular array internally, which increases in size when the current array is filled.
Main points:
- Elements are stored in an array.
- When a new element is added and the array is full, a new array of larger size (usually 50% larger or twice as large) is created, and old elements are copied into it.
- Access to elements by index occurs in constant time O(1).
- Adding an element at the end is usually O(1), but during array expansion, it is O(n).
Example usage:
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
String first = list.get(0);