简体   繁体   中英

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

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!

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.

ArrayList.add(0, element)占用线性时间,但常量非常低,因为它可以使用超快速的System.arraycopy

The ArrayList documentation is indeed obscure on this point -- I looked at it in SE11 just now, and it's unchanged since the first release of the Collections Framework (in Java 1.2).

I believe the intent of the authors of the ArrayList documentation was to specify that, on any implementation of Java, the appending operation (ie the add(E e) method) must run in constant amortized time, and that the list insertion operation (ie the add(int index, E e) method) must run in O(n) time, where n is the size of the list.

  • Building the list from scratch and adding lots of elements to the beginning runs in quadratic time: O(n 2 ).
  • Adding all elements to the end of the list and then calling Collections.reverse(list) runs in linear time: O(n).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM