Search code examples
javaarraylistarraydeque

Can We replace ArrayList with ArrayDeque for better performance?


I was reading Kathy sierra's OCP8 guide and found a line that says:

"ArrayDeque is like an ArrayList with better performance"

Now I am confused about where to use ArrayList and where to use ArrayDeque. I also know that ArrayDeque is always resized to a power of 2. On resize, the capacity is doubled, so this might be a performance hit in some cases. But I want to know which is preferable between the two. Help is much appreciated.


Solution

  • i would suggest use ArrayList over ArrayDeque on below cases

    1. Use an ArrayList if you need to access elements by index and you only need to insert/delete at the end.
    2. Use an ArrayDeque as a stack, queue, or deque.

    Insertion and Deletion in Both Collection.

    ArrayList:

    Worst-case O(n) because you have to shift elements. Insertion/deletion at the end is faster because there are fewer elements to shift. If you insert when the Arraylist is full, you have to copy the elements into a new larger array, which is O(n).

    • Insertion at the end of an ArrayList takes amortized constant time. This means that a sequence of n insertions into an initially empty ArrayList has a worst-case runtime of O(n), so the average runtime per insertion is O(1), although some insertions may be slower. This is achieved by always increasing the array size by a constant factor, because the total number of elements copied is the sum of a geometric series.

    ArrayDeque:

    • Deletion at the front or back is O(1), and insertion at the front or back takes amortized constant time. The JCF implementation does not allow insertion/deletion by index (if it was allowed, it would be worst-case O(n) because of shifting).
    • Array deques have no capacity restrictions and they grow as necessary to support usage.
    • They are not thread-safe which means that in the absence of external synchronization
    • Null elements are prohibited in the ArrayDeque.

    now answer is in your question. its totally depend on your requirement.after analysing you can easily predict.

    for more please take a look