Search code examples
javalistarraylistqueuearraydeque

ArrayList VS ArrayDeque in shifting elements?


I tried asking a similar question, but I failed to receive any satisfying answer. The motivation behind this question is this question's first (accepted) answer that roughly says:

ArrayDeque doesn't have the overhead of shifting contents like ArrayList.

From my point of view, they should act the same. The only difference is that ArrayList is implemented from List interface, meaning it can access any arbitrary index. On the other side, ArrayDeque is implemented from Queue interface and it works in LIFO/FIFO manner.

The thing I want to point is that they both use AN ARRAY to store elements. Meaning if they both had an array with these elements:

2, 4, 6, 8, 10

, doing arraylist.remove(0); and arraydeque.poll(); should both remove first/head element with value 2.

Now my big question. Do all those left numbers (4,6,8,10) get shifted to left for 1 slot in both cases? Is there any difference between ArrayList and ArrayDeque in way how they shift elements when we do any structure modification?


Solution

  • In ArrayList, each of the elements gets shifted over.

    In ArrayDeque, the elements don't move in the array. The pointer in the array that says where the current head of the queue is gets moved over.

    (Why doesn't ArrayList do this, you might ask? It could conceivably do it, but it'd only work for inserting/removing elements at the beginning and end, not in the middle. ArrayList isn't really designed to be used that way -- if you're doing that, then you have a queue/deque, so you might as well use ArrayDeque.)