// Array implementation of Queue Queue<String> animal2 = new ArrayDeque<>(); // LinkedList implementation of Queue Queue<String> animal1 = new LinkedList<>(); // Priority Queue implementation of Queue Queue<String> animal 3 = new PriorityQueue<>();
/**
* @author lautturi.com
* Java example: java queue
*/
import java.util.*;
public class Lautturi {
public static void main(String args[]) {
// use non-primative types when constructing
Queue<Integer> queue = new LinkedList<Integer>();
// adds a value to the back of queue:
queue.add(1);
queue.add(3);
queue.add(5);
queue.add(2);
queue.add(4);
queue.add(6);
//print the contents of the Queue
System.out.println("Queue:"+queue);
// removes first element from the queue
int first = queue.remove();
System.out.println("first:"+first);
System.out.println("Queue:"+queue);
// just returns front value without removing:
int peek = queue.peek();
System.out.println("peek:"+peek);
System.out.println("Queue:"+queue);
// returns head of the queue
int element = queue.element();
System.out.println("element:"+element);
System.out.println("Queue:"+queue);
// removes and returns the head
int poll = queue.poll();
System.out.println("poll:"+poll);
System.out.println("Queue:"+queue);
}
}
output:
Queue:[1, 3, 5, 2, 4, 6] first:1 Queue:[3, 5, 2, 4, 6] peek:3 Queue:[3, 5, 2, 4, 6] element:3 Queue:[3, 5, 2, 4, 6] poll:3 Queue:[5, 2, 4, 6]