Sobes.tech
Junior — Middle

How is the index of an element determined when accessing an element in an ArrayList, and what is the resulting time complexity?

sobes.tech AI

Answer from AI

In ArrayList, elements are stored in an array, so the index of an element corresponds to its position in this array. When accessing an element by index, ArrayList simply calculates the address in the array and returns the value.

Access time complexity by index is O(1) (constant), as access to an array element occurs directly without iteration.

Example:

ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
String element = list.get(1); // Retrieves "B" in O(1)
How is the index of an element determined when… - sobes.tech