Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of adding an element at the beginning of an ArrayList?

Tags:

java

Say I have a ArrayList with n element in this array, and I add an element at the beginning:

myArrayList.add(0,'some value');

What will be the time complexity of this operation?

The Java Doc doesn't specify this.

Also

I just start learning Java, and I saw the sentence

An ArrayList in Java is a List that is backed by an array.

What does 'backed' here mean? Thank you!

like image 480
lakeskysea Avatar asked May 27 '13 17:05

lakeskysea


1 Answers

Adding an element to beginning of array is O(n) - it would require to shift all the existing elements by one position.

All elements in an array list are stored in a contiguous array. If you add more elements than the current size of the array - it will be grown automatically to accommodate the new element.

Addition to the end is O(1) amortized over multiple insertions.

like image 103
gkamal Avatar answered Sep 21 '22 16:09

gkamal