Junior — Middle
How is the access time to the first element in ArrayList determined?
sobes.tech AI
Answer from AI
In Java, the ArrayList class is implemented based on a dynamic array. Access time to the first element (or any element by index) is constant, that is O(1). This is because elements are stored in a contiguous block of memory, and access to an element by index is done directly through offset calculation.
Example:
ArrayList<String> list = new ArrayList<>();
list.add("First");
list.add("Second");
String first = list.get(0); // access to the first element in O(1)