Difference in LinkedList, queue vs list
Solution 1
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!
Solution 2
In the both the cases, you are instantiating LinkedList
.
The difference is the types of the variables you use to refer to those instances.
test
is of type Queue
and test2
is of type List
. Depending on the type of variable, you only get to invoke the methods which are specified on that particular type. I think this what matters for your situation.
Performance-wise, it's going to be the same, because the actual implementation that you are using in both the cases is same (LinkedList
).
Solution 3
I feel both of them are pretty much same except that the type of methods you are going to expose. As LinkedList implements both the interfaces, so choosing one of them opens up access to methods of that interface type.
please take a look at these links for interface method declarations
http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html http://docs.oracle.com/javase/6/docs/api/java/util/List.html
i am not sure about the performance, though i guess it shouldn't be different as the object implementation is common.
Kailua Bum
Updated on July 09, 2022Comments
-
Kailua Bum almost 2 years
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
andtest2
? Are both of themLinkedList
? Are there performance differences or reasons to use one over the other?