Difference in LinkedList, queue vs list

Kailua Bum picture Kailua Bum · Mar 25, 2013 · Viewed 22.6k times · Source

What is the difference when creating these two objects

Queue<String> test = new LinkedList<String>();

and

List<String> test2 = new LinkedList<String>();

What are the actual differences between test and test2? Are both of them LinkedList ? Are there performance differences or reasons to use one over the other?

Answer

templatetypedef picture templatetypedef · Mar 25, 2013

The two statements you've written each construct a LinkedList<String> object to hold a list of strings, then assign it to a variable. The difference is in the type of the variable.

By assigning the LinkedList<String> to a variable of type Queue<String>, you can only access the methods in the LinkedList that are available in the Queue<String> interface, which includes support for enqueuing and dequeuing elements. This would be useful if you needed to write a program that used a queue for various operations and wanted to implement that queue by using a linked list.

By assigning the LinkedList<String> to a variable of type List<String>, you can only access the methods in the LinkedList that are available in the List<String> interface, which are normal operations for maintaining a sequence of elements. This would be useful, for example, if you needed to process a list of elements that could grow and shrink anywhere.

In short, the two lines create the same object but intend to use them in different ways. One says that it needs a queue backed by a linked list, while the other says that it needs a general sequence of elements backed by a linked list.

Hope this helps!