简体   繁体   中英

How does List.add(index,element) work internally in Java?

As mentioned in Java API Doc and this post , the list.add(index,element) results in the given element being added at the given index. In the process, the subsequent list items are shifted by one position to the right (by adding one to their indices as mentioned in the API Doc)

My question is how does this happen practically?

Suppose we have an ArrayList containing 100 elements and we say add(0, 6) , now how would the API accomplish this action, given the fact that the underlying Data Structure is an array?

More specifically: Would all the existing 100 elements be copied to its immediate right location? Or is there a more efficient way by which this is handled?

For an ArrayList the elements will indeed be moved up. This is just linear memory access so actually surprisingly fast.

Inserting at the front is faster with an ArrayDeque , which uses a cyclic buffer. That is, not only does it keep track of the last element index, but also the first and the array wraps around. Unfortunately, ArrayDeque does not implement List which it arguably should do.

The very slow LinkedList can remove the first element quickly but is generally very slow.

The source code for all of these classes is freely available and not too complex.

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