I came to know that in Java, LinkedList
class implements both Deque
and List
interfaces.
And this was somewhat confusing to me.
In computer science syllabus, I was never taught that queue can be a list, or more precisely queue can behave like a list. That is, there is stuff that lists can do, but queues can't. But the list can behave like a queue. For example, List
interface has the following methods:
add(E e)
add(int index, E element)
But Queue
has only the following:
add(E e)
So clearly Queue
is not allowed to insert at specific index, which is allowed in List
. The same is the case with other operations like Queue.remove()
vs. List.remove(int index)
, List.get(int index)
vs. Queue.peek()
.
In other words, list is a more generalized data structure and can emulate Queue
.
Now being capable to emulate is different from having a contract subset. That is, Queue
disallows certain operations (indexing) of List
and allows certain operations done only in a particular manner (insert only at the tail and remove only from the head). So Queue
does not really do "addition" to the contracts of List
. That is precisely why Queue
does not extend List
in Java collections framework, but both extend Collection
interface. I believe that is also why it's incorrect for any class to implement both, as Queue
's contract conflicts with the contract of List
(which is why they fork out from Collection
interface separately). However, LinkedList
implements both the interfaces.
I also came across this answer:
The
LinkedList
implementation happens to satisfy theDeque
contract, so why not make it implement the interface?
I still don't get how we can say "LinkedList
implementation happens to satisfy the Deque
contract". The concept of a queue does not allow insertion at an arbitrary index. Hence, the Queue
interface does not have such methods.
However we can only enforce contracts through interfaces and cannot disallow implementation of certain methods. Being list (having "List" in its name), I feel it's not correct to have queue methods peek()
, pop()
and add(int index, E element)
in LinkedList
.
I believe, instead we should have separate class LinkedQueue
which can have linked implementation for queue, similar to LinkedBlockingQueue
which contains linked implementation of BlockingQueue
.
Also note that LinkedList
is the only class which inherits from both families of lists and queues, that is, there is no other class which implements both List
and Queue
(AFAIK). Can this be indication that LinkedList
is ill done?
Am I plain wrong and thinking unnecessarily?