Junior — Middle
How is the access time to the last element in an ArrayList determined?
sobes.tech AI
Answer from AI
Access time to the last element in an ArrayList in Java is O(1) — constant time. This is because ArrayList is implemented based on an array, and elements are stored in a contiguous block of memory.
To access an element by index, ArrayList simply calculates the address of the element as the base address of the array plus an offset, which takes a fixed amount of time regardless of the size of the list.
Example:
ArrayList<String> list = new ArrayList<>();
list.add("First");
list.add("Second");
String last = list.get(list.size() - 1); // access to the last element in O(1)