Use:
Queue<Object> queue = new LinkedList<>();
You can use .offer(E e) to append an element to the end of the queue and .poll() to dequeue and retrieve the head (first element) of the queue.
Java defined the interface Queue, the LinkedList provided an implementation.
It also maintains references to the Head and Tail elements, which you can get by .getFirst() and .getLast() respectively.
credit to @Snicolas for suggesting queue interface
Answer from didxga on Stack OverflowVideos
Use:
Queue<Object> queue = new LinkedList<>();
You can use .offer(E e) to append an element to the end of the queue and .poll() to dequeue and retrieve the head (first element) of the queue.
Java defined the interface Queue, the LinkedList provided an implementation.
It also maintains references to the Head and Tail elements, which you can get by .getFirst() and .getLast() respectively.
credit to @Snicolas for suggesting queue interface
If you use LinkedList be careful. If you use it like this:
LinkedList<String> queue = new LinkedList<String>();
then you can violate queue definition, because it is possible to remove other elements than first (there are such methods in LinkedList).
But if you use it like this:
Queue<String> queue = new LinkedList<String>();
it should be ok,as this is heads-up to users that insertions should occur only at the back and deletions only at the front.
You can overcome defective implementation of the Queue interface by extending the LinkedList class to a PureQueue class that throws UnsupportedOperationException of any of the offending methods. Or you can take approach with aggreagation by creating PureQueue with only one field which is type LinkedList object, list, and the only methods will be a default constructor, a copy constructor, isEmpty(), size(), add(E element), remove(), and element(). All those methods should be one-liners, as for example:
/**
* Retrieves and removes the head of this queue.
* The worstTime(n) is constant and averageTime(n) is constant.
*
* @return the head of this queue.
* @throws NoSuchElementException if this queue is empty.
*/
public E remove()
{
return list.removeFirst();
} // method remove()
If you are using Java 8, you can create a queue of IntSupplier like this:
Queue<IntSupplier> queue = // some new queue
queue.add(() -> add(10, 20));
queue.add(() -> add(20, 30));
// The getAsInt-method calls the supplier and gets its value.
int result1 = queue.remove().getAsInt();
int result2 = queue.remove().getAsInt();
Using Java8:
@Test
public void test(){
QueueMethod q1= ()->System.out.println("q1 hello");
QueueMethod q2= ()->System.out.println("q2 hello");
Queue<QueueMethod> queues=new LinkedList<QueueMethod>();
queues.add(q1);
queues.add(q2);
queues.forEach(q->q.invoke());
}
@FunctionalInterface
interface QueueMethod{
void invoke();
}
Output:
q1 hello
q2 hello