18

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 Listand 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 the Deque 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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MsA
  • 2,599
  • 3
  • 22
  • 47
  • 16
    Linked List implements Deque and List. This **does not** mean that Deque is a List. Rather, both Deque and List can be implemented as a Linked List. – pmcarpan Oct 20 '18 at 09:31
  • 2
    The datastructure, as `LinkedList` is currently written, represents a valid implementation for all those interfaces. So it is only natural to declare that it is all of them. You are wrong with your first paragraph. A `Queue` does in fact not have the methods a `List` has. But that is why we do not have `Queue implements List`. `LinkedList` is both of them, this does not imply that a `Queue` now is a `List`. – Zabuzard Oct 20 '18 at 09:32
  • 7
    The question is **well asked** though, so have my up-vote. Don't know why people are down-voting, maybe because they think it's *silly* (but that is no valid reason to down-vote). – Zabuzard Oct 20 '18 at 09:34
  • 2
    Any interface doesn't prevent an implementation supporting more operations. (Except where overloaded methods conflict) – Peter Lawrey Oct 20 '18 at 09:57
  • The answers are saying you're missing the point but I think you are absolutely correct. Doing `class A implements B, C` does not imply that a A can be thought of as a B or as a C, it means that it is simultaneously a B and a C. There is a [violated invariant](https://en.wikipedia.org/wiki/Liskov_substitution_principle) of a queue type here (that you cannot modify elements in its middle) so it is incorrect subtyping. The actual argument that should be had is "whether or not a queue requires that elements can't be modified in the middle or only that they can be modified in the ends in FIFO". – Benjamin Gruenbaum Oct 21 '18 at 12:36
  • I added an answer that cites the LSP. PTAL. – Benjamin Gruenbaum Oct 21 '18 at 12:44
  • *In computer science syllabus, I was never taught that queue can be a list*. I am curious what syllabus you are referring to. Because at least in CLSR, there is a problem (10.2-3) that explicitly says: *Implement a queue by a singly linked list*. – jrook Oct 25 '18 at 04:49

5 Answers5

45

You're entirely missing the point of programming to interface.

If you need a Queue, you never write:

LinkedList<String> queue = new LinkedList<>();

Because, you're right, that would allow you to use non-queue methods. Instead, you program to the interface like this:

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

Now you only have access to the 6 Queue methods (and all the Collection methods). So, even though LinkedList implements more methods, you no longer have access to them.

So, if you need a Queue, you choose the implementation of the Queue interface that best suits the performance, storage, and access characteristics you need, e.g.


I was never taught that queue can be a list, or more precisely queue can behave like a list.

Remember that implements defines a behaves like relationship. A LinkedList behaves like a List. A LinkedList behaves like a Deque. A LinkedList behaves like a Queue.

But just because LinkedList behaves like all of those, doesn't mean that List behaves like a Queue or that Queue behaves like a List. They do not.

The behaves like relation only goes one way.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 1
    Now I am guessing why there is no `Stack` interface implemented by `LinkedList` as it also have `push()` and `pop()` methods. Surely it sounds wrong to do `linkedListObj.push()`. Is this something to do with `java.util.Stack`? – MsA Oct 20 '18 at 11:30
  • 3
    @anir Yes, unfortunately they implemented `Stack` as a class, not an interface, way back in the beginning, and we're now stuck with it. As the javadoc of [`Stack`](https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html) says: *"A more complete and consistent set of LIFO stack operations is provided by the [`Deque`](https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html) interface and its implementations, which should be used in preference to this class."* – Andreas Oct 20 '18 at 20:04
  • I disagree with this answer because it implies that [substitution does not need to preserve invariants](https://en.wikipedia.org/wiki/Liskov_substitution_principle). If I can substitute Queue with a LinkedList and then violate its invariant that elements are accessed in FIFO matter it is incorrect in terms of OOP purity. It is an _entirely valid and reasonable tradeoff_ but it is still not a tradeoff that should be ignored and I think it is rude to say OP is "entirely missing the point" because they are concerned by it. – Benjamin Gruenbaum Oct 21 '18 at 12:38
  • I agree with this answer. Simpler languages do not offer something like `Queue queue = new LinkedList<>();` where one has the (also future) choice of several implementing classes, and can still work against a clean API (`Queue`). Computer Science in my time only treated a Stack as type, and came not further than one implementation; and then maybe a concurrent implementation. But reusing classes like LinkedList were not a subject. Java has many good design choices, and admittedly sufficient weaknesses. – Joop Eggen Oct 22 '18 at 07:13
6

@Andreas's answer is excellent, so mine targets your arguments about what you were or were not taught:

In computer science syllabus, I was never taught that queue can be a list or more precisely queue can behave like a list

A queue is not just any list, but a special kind of list, with its own special properties and constraints.

That is, there is stuff that lists can do, but queues can't.

No, List can do nothing. It provides possibilities to be implemented by a class and if that class decides to implement them then that class can do all that stuff.

But the list can behave like a queue.

No, List does not behave; it only suggests behaviors and classes that implement it can accept all or a subset of them or they can define new ones.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
forpas
  • 160,666
  • 10
  • 38
  • 76
  • 1
    *"A queue is a special kind of list"* Not always, e.g. a [`PriorityQueue`](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html) is a heap, not a list. --- *"`List` does not behave"* That is about the only thing it does: *Behave*. The `List` interface is a contract of behavior, e.g. *"if you call `add(2, "X")` the result must be that `"X"` is the third value in the list"*. Any class implementing the interface must "behave" the way the interface describes. It doesn't matter which class implements the `List`, the `List` *will* behave according to the contract. – Andreas Oct 20 '18 at 10:56
  • @Andreas *The List interface is a contract of behavior* you said it. List does not behave because it is not *real*, its implementations are real and can behave. As for the PriorityQueue: what I state in my answer is not Java specific, but rather academic. The concept of a priority queue and any queue is a subset of lists regardless how any language decides to implement its mechanics. – forpas Oct 20 '18 at 11:04
  • If my code has a `List`, it is very real. I may not know how it is realized (implemented), but if it wasn't real, I couldn't use it, and it behaves exactly like I expect. The **`List` interface** declaration defines a contract, but **a list** (an object of the `List` interface) is real and it behaves. --- My first comment was trying to say that your terminology is confusing / misleading. – Andreas Oct 20 '18 at 11:13
  • @Andreas so what are we arguing about? In my answer when I refer to `List` I mean the interface because this was OP's question. Of course an instantiated List object is real because it accepts and implements everything in the *contract of behavior* of the `List` interface. – forpas Oct 20 '18 at 11:20
  • 3
    *"In computer science syllabus, I was never taught that queue can be a list or more precisely queue can behave like a list ..."* There are lots of things that are not explicitly spelled out in a University level course. Rather students are expected to develop the understanding and the mental skills to work these things out for themselves. – Stephen C Oct 20 '18 at 11:59
4

LinkedList is a class that implements both List and Deque interfaces. Each one of these interfaces defines a contract with operations, and in these contracts it is specified what these operations must do. However, it is not specified how these operations are supposed to work.

LinkedList is a class that implements both List and Deque interfaces. So, despite the suffix List is part of the name of the LinkedList class, LinkedList is actually both a List and a Deque, because it implements all of the operations that are defined in the List and Deque interfaces.

So LinkedList is a a List, and it also is a Deque. This doesn't mean that a List should be a Deque, or that a Deque should be a List.

For example, look at the following interfaces:

public interface BloodDrinker {

    void drinkBlood();
}

public interface FlyingInsect {

    void flyAround();
}

Each one of the interfaces above has a single operation and defines a contract. The drinkBlood operation defines what a BloodDrinker must do, but not how. Same applies for a FlyingInsect: its flyAround operation defines what it must do, but not how.

Now consider the Mosquito class:

public class Mosquito implements FlyingInsect, BloodDrinker {

    public void flyAround() {
        // fly by moving wings, 
        // buzzing and bothering everyone around
    }

    public void drinkBlood() {
        // drink blood by biting other animals:
        // suck their blood and inject saliva
    }
}

Now, this means that a Mosquito is both a FlyingInsect and a BloodDrinker, but why would a blood drinker necessarily be a flying insect, or a flying insect necessarily be a blood drinker? For example, vampires are blood drinkers, but not flying insects, while butterflies are flying insects, but not blood drinkers.


Now, with regard to your argument about Queue disallowing certain List's operations (indexing), and only allowing addition/removal on its ends in a FIFO fashion... I don't think this rationale is correct, at least in the context of the Java Collections Framework. The contract of Deque doesn't explicitly mention that implementors will never ever be able to add/remove/check elements at any given index. It just says that a Deque is:

A linear collection that supports element insertion and removal at both ends.

And it also says that:

This interface defines methods to access the elements at both ends of the deque.

(Emphasis mine).

A few paragraphs later, it does explicitly say that:

Unlike the List interface, this interface does not provide support for indexed access to elements.

(Emphasis mine again).

The key part here is does not provide support. It never forbids implementors to access elements via indexes. It's just that indexed access is not supported through the Deque interface.

Think of my example above: why would a BloodDrinker disallow its implementors to drink something other than blood, i.e. water? Or why would a FlyingInsect disallow its implementors to move in a way different than flying, i.e. walking?

Bottom line, an implementation can adhere to as many contracts as it wishes, as long as these contracts don't contradict each other. And as it's worded in Java (a very careful and subtle wording, I must admit), Deque's contract doesn't contradict List's contract, so there can perfectly exist a class that implements both interfaces, and this happens to be LinkedList.

fps
  • 33,623
  • 8
  • 55
  • 110
1

You are starting from a weak premise:

I was never taught that queue can be a list.

Let us go back to the basics. So what are data structures anyway? Here is how CLSR approaches that question1:

...Whereas mathematical sets are unchanging, the sets manipulated by algorithms can grow, shrink, or otherwise change over time.

Mathematically, data structures are just sets; dynamic sets. In that sense, a queue can be a list. In fact, there is a problem in CLSR (10.2-3) that explicitly asks you to implement a queue by using a linked list.

On the other hand, object-oriented programming is a paradigm that helps programmers solve problems by adhering to a certain philosophy about the problem and the data. Objects, interfaces, and contracts are all part of this philosophy. Using this paradigm helps us implement the abstract concept of dynamic sets. However, it comes with its own baggage, one of them being the very problem asked about here.

So if you are complaining that the data structures in Java standard library do not strictly adhere to the conventions defined for elementary data structures, you are right. In fact, we do not even need to look further than java.util.Stack to see this2. You are also allowed to roll out your own implementation in any way you want and use them instead of standard library collections.

But to argue that Java, or its standard library for that matter, is broken or ill-done - an extraoridnary claim- you need to be very specific about the use case and clearly demonstrate how the alleged flaw in the library prevents you from achieving the design goals.


1 Introduction to Chapter III, p220

2 Sedgewick and Wayne call java.util.Stack a "wide interface"(p 160) because it allows random access to stack elements; something a stack -as defined in elementary data structures- is not supposed to be capable of.

jrook
  • 3,459
  • 1
  • 16
  • 33
-1

You are entirely correct in this and not missing the point at all. Java simply made a trade-off between correctness and ease. Making it implement both interfaces was the easy thing to do and the one that was the most useful for developers.

What subtyping means

Correct (sound) subtyping requires substitution to work which requires according to the LSP:

Invariants of the supertype must be preserved in a subtype.

When we say in type theory "A LinkedList is a List and a Queue" we are actually saying that a LinkedList is both a list and a queue at the same time and not that a LinkedList can be thought of as either a list or a queue.

There is a violated invariant of a queue type here (that you cannot modify elements in its middle) so it is incorrect subtyping.

The actual argument that should be had is "whether or not a queue requires that elements can't be modified in the middle or only that they can be modified in the ends in FIFO".

One might argue that the invariants of a Queue are only that you can use it in a FIFO matter and not that you must. That is not the common interpertation of a queue.

Hulk
  • 6,399
  • 1
  • 30
  • 52
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    There are multiple `Queue`-implementations that are not FIFO - examples: [DelayQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/DelayQueue.html), [PriorityQueue](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html). Most `Queue` implementations in java allow iteration and removal of elements at arbitrary indices via their iterators. And then there is [SynchronousQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/SynchronousQueue.html), which never really contains elements. The `Queue`-contract is worded in a way that allows all that. – Hulk Oct 22 '18 at 06:29