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

后端 未结 4 1128
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 19:55

    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 (i.e. the add(E e) method) must run in constant amortized time, and that the list insertion operation (i.e. the add(int index, E e) method) must run in O(n) time, where n is the size of the list.

提交回复
热议问题