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

后端 未结 4 1120
Happy的楠姐
Happy的楠姐 2021-02-13 19:32

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

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 20:06

    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.

提交回复
热议问题