问题
The documentation says:
Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage
However I still want to understand what exactly the structure of ArrayDeque is, how the resizing works. Also it would be great if someone could provide a reliable source where I can find the answer. According to some of the Google results I found, it is possibly implemented as a circular array. Is it true? And what is the grow policy? Is it similar to ArrayList? If it is, does ArrayDeque have a similar performance to ArrayList in the operations like adding or removing the element at the end?
Thank you.
回答1:
The grow policy of ArrayList
and ArrayDeque
is not documented and may vary between JDK implementations and even JDK versions. For example, in Open JDK 6 it was (n*3/2+1)
, but in Open JDK 8 it's (n*3/2)
. Also in JDK 6 ArrayList
with default constructor was initially created with 10 elements array while in JDK 8 it allocates an array only when at least one element is added.
The ArrayDeque implementation changes less often than ArrayList
. It always uses internally the power-of-two sized array starting with 16
by default and doubling it when necessary, thus memory footprint may be different for ArrayList
and ArrayDeque
(for ArrayDeque
you will have in average less reallocations, but more wasted memory).
Addition to the tail is roughly equally fast for both ArrayList
and ArrayDeque
unless reallocation is necessary. Reallocation events may occur at different points. For example, by default first reallocation for ArrayList
will occur when adding element #11, but for ArrayDeque
it will occur on element #16.
The advantage of ArrayDeque
is ability to add/remove elements to the head as fast as to the tail. In contrast, ArrayList
will do it in O(n)
time as it will have to move all the existing elements. Thus use ArrayDeque
when you need to add/remove both to head and tail. If you need to modify the tail only, usually ArrayList
is preferred.
来源:https://stackoverflow.com/questions/31375292/about-implementation-of-arraydeque-in-java