The best resource is straight from the official API:
Answer from brian_d on Stack OverflowThe size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Why is the add(index, element) time complexity not constant in Java for array lists?
For array lists, you would have to move all elements to adjacent positions when you insert at an index. So it takes linear time ( more the number of elements already in the list, more time it takes to move them all ).
Also Java has nothing to do with time complexities of a data structure. It is universal.
More on reddit.comTime complexity for java ArrayList - Stack Overflow
Analyzing time complexity of Java methods
What is the complexity of contains method of HashSet?
Videos
If a simple add(element) takes constant time because we need to add to the end only, why does the other add(index, element) take linear time instead? I just started studying data structures and algorithms, so any advice would help.
For array lists, you would have to move all elements to adjacent positions when you insert at an index. So it takes linear time ( more the number of elements already in the list, more time it takes to move them all ).
Also Java has nothing to do with time complexities of a data structure. It is universal.
Because you can't just plop the element into the center of an array let's say. You put it in that place then have to shift all other elements to the right after it. For linkedlist where the actual insert is constant, finding the xth element would take linear time. Constant (adding to very end of list) is best case scenario bit linear is most realistic for it's use case.
An ArrayList in Java is a List that is backed by an array.
The get(index) method is a constant time, O(1), operation.
The code straight out of the Java library for ArrayList.get(index):
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
Basically, it just returns a value straight out of the backing array. (RangeCheck(index)) is also constant time)
It's implementation is done with an array and the get operation is O(1).
javadoc says:
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.