I quickly wrote a linked list class in Java. I want to write another queue class which uses the linked list. How would I achieve this in Java? I don't fully understand the implements / extends keywords... this is what my queue looks like ( for example):
public class Queue<T> implements LinkedList
{
protected LinkedList<T> list;
public Queue() {
list = new LinkedList<T>();
}
public void add( T element) {
list.add( element);
}
public T removeLast() {
return list.removeLast();
}
}
Also note that the linked list class is also generic. I know there are already built in classes to achieve this functionality, but I wanted to learn ( which is why I am trying to do this manually)
EDIT: Additionally, in the end, I would like to be able to say something like this:
Queue<String> aQueue = new LinkedList<String>();
If you want a behavior like
Queue<String> aQueue = new LinkedList<String>();
then yourLinkedList
must extend/implement theQueue
class/interface. Remember that a super class can be the object reference instance of a sub class, not viceversa.Also, as the Java documentation states,
Queue
is an interface andLinkedList
implements it.Note: If you want to implement a Queue using your LinkedList, you should see the code sample posted by @Tudor.
Since Linkedlist implements queue interface we can use poll, peek methods directly....no need of extra code
Two mistakes in your code:
You are both implementing
LinkedList
(did you mean extend?) and using composition by having aLinkedList
inside your class.This piece of code will not work:
Queue<String> aQueue = new LinkedList<String>();
because according to point 1,Queue
is either a subclass ofLinkedList
or contains aLinkedList
, which makes your code incorrect.In fact, the last code snippet makes very little sense. I assume that what you want to do is create a
Queue
that internally uses a linked list. In that case just use:And then: