0

I was trying to understand the In-built Queue Interface in Java. I understood how to use the class well.

But I cannot Understand why does it use LinkedList Constructor to initiate itself?

why is it needed? Cannot we implement a queue using an ArrayList?

Thanks in Advance

3
  • What Queue class? java.util.Queue is an interface. Commented Mar 19, 2019 at 13:19
  • Wooops! Thanks Edited :D Commented Mar 19, 2019 at 13:20
  • I would expect this to be based on the common use of a queue, involving multiple (perhaps many) changes to the elements. ArrayList and Array and such would have more to do adjusting the length and so forth, whereas a linked list is easier to add to and substract from. Commented Mar 19, 2019 at 13:29

1 Answer 1

1

Because LinkedList implements Queue, whereas ArrayList does not.

Queue<Object> myQueue = new LinkedList<>(); // Works, LinkedList implements Queue
Queue<Object> myQueue = new ArrayList<>(); // Doesn't compile, ArrayList doesn't implement queue

Now, if you so wished, you could write a new class implementing Queue, and using an ArrayList as its backing container, but I don't see the appeal since you can already initialize a LinkedList from an ArrayList. Arguably, there could be some performance on the List methods (if you implemented it too) but there would be little to none on the Queue methods.

Sources: Javadoc for Queue, LinkedList and ArrayList

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.