1

I do not understand the difference between LinkedList and Deque in Java

LinkedList<Integer> linkedList = new LinkedList<>();
Deque<Integer> myDeque = new LinkedList<>();

Both of these allow inserting and deleting elements from the front and the end. Both of these have methods such as addFirst, addLast and removeFirst and removeLast.

linkedList.addFirst(1);
linkedList.addLast(2);
System.out.println(linkedList);

myDeque.addFirst(1);
myDeque.addLast(2);
System.out.println(myDeque);

Also, I do not understand why LinkedList should permit inserting elements from the front, since this is a custom requirement. By the same logic, LinkedList should also have custom methods for getting the smallest and largest element?

saltandwater
  • 791
  • 2
  • 9
  • 25
  • Have you looked at the source code for LinkedList and Deque? – Jonny Henly Aug 18 '16 at 03:10
  • @JonnyHenly, sorry I haven't. I was asking from a working point of view with regards to how the two data structures behave. Don't they behave the same? – saltandwater Aug 18 '16 at 03:14
  • They both implement the `List` interface (and possibly other interfaces), but they do not work the same. An interface is like a contract and when a class implements an interface it has to define the methods listed in that interface. – Jonny Henly Aug 18 '16 at 03:16
  • @JonnyHenly, hmm. From a coding point of view, can you please give me an example of a difference. – saltandwater Aug 18 '16 at 03:20
  • I was wrong in my last comment, they don't both implement `List`. `LinkedList` implements `Collection` and since `Deque` is an interface, it extends `Collection`. This Stack Overflow question: [Why is ArrayDeque better than LinkedList?](http://stackoverflow.com/questions/6163166/why-is-arraydeque-better-than-linkedlist) should provide you with some differences. Note that `ArrayDeque` implements `Deque`. – Jonny Henly Aug 18 '16 at 03:33
  • Deque is an LIFO (Last-In-First-Out) stack interface. It defines method every implementation must have. Interfaces allows you to use its implementations with out any knowledge about there real type(polymorphism). And LinkedList is simple one of it's implementations. In case `Deque myDeque = new LinkedList<>();` all you following code use an object of type Deque, so you can simply replace the implementation type any time with no changes to other code. – Konstantin Labun Aug 18 '16 at 04:30

0 Answers0