Junior
What data structure is used in ArrayList?
sobes.tech AI
Answer from AI
An ArrayList uses an array.
- When adding elements, if the current array is full, a new, larger array is created, and elements are copied from the old array to the new one.
- Access to elements by index is O(1).
- Insertion and deletion in the middle of the list require shifting elements, which takes O(n).
- Insertion and deletion at the end of the list, if no array resizing is needed, take O(1).
// Example of creating and using ArrayList
import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(); // Internally uses an array
list.add("Element 1");
list.add("Element 2");
System.out.println(list.get(0)); // Index access O(1)
}
}