So, I assume that ArrayLists are stored on the heap in contiguous places (thats the reason they have the O (1) get method).
All other answers here are correct, but I want to turn to the incorrect assumption that you made here:
ArrayList.get() is O (1) not because of how the array is stored in memory, but because the cost of accessing an element is constant and not proportional to the number of elements in ArrayList.
O (1) here does not mean that the search can be performed in one operation - this means that the complexity is constant in relation to the size of the support array.
When you call ArrayList.get(i) , the JVM still needs to translate the array index into a virtual memory address in which your OS translates the address into real, but it is O (1), because the complexity is the same, the array has 1 element or 5000.
For comparison, LinkedList.get(i) not O (1), because the LinkedList class must go through each node until it finds node i - the complexity is proportional to the total size of the list and the value of i .
The assumption that the array is stored in contiguous places is also incorrect.
source share