1

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?

1
  • 1
    Why not just look at the source code if you want to see how it is done? You can find it in the link I provided for you, and you can find it in the JDK you have installed. Very easy to look at that source code if you're using a good IDE. You are using an IDE, right? If not, save yourself a lot of hassle and get one now. Commented Dec 14, 2019 at 3:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.