0

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.

1 Answer 1

2

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

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

2 Comments

You say Use an ArrayList if you need to access elements by index and you only need to insert/delete at the end. But if we need to insert at ends , LinkedList is preferred over ArrayList.
@Codeninja exactly, but you need to traverse whole linked list. but you can do insertion using index method

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.