package collectionQueue; import java.util.LinkedList; import java.util.Queue; public class MainQueue { public static void main(String[] args) { System.out.println("\nQueue in Java\n"); System.out.println("-----------------------\n"); System.out.println("Adding items to the Queue"); // Creating queue would require you to create instannce of LinkedList // and assign // it to Queue // Object. You cannot create an instance of Queue as it is abstract Queue queue = new LinkedList(); // Queue with a limited number of elements. // //Queue queueTwo = new ArrayBlockingQueue(2); // queueTwo.offer("hi"); // queueTwo.offer("there"); // queueTwo.offer("you"); // for(String x: queueTwo) // System.out.println(x); // you add elements to queue using add method queue.add("Java"); queue.add("has"); queue.add("its own"); queue.add("Queue"); queue.add("Interface"); System.out.println("\nItems in the queue..." + queue + "\n"); // You remove element from the queue using .remove method // This would remove the first element added to the queue, here Java System.out.println("remove element: " + queue.remove() + "\n"); // .element() returns the current element in the queue, here when "java" // is removed // the next most top element is "has", so "has" would be printed. System.out.println("retrieve element: " + queue.element() + "\n"); // .poll() method retrieves and removes the head of this queue // or return null if this queue is empty. Here "has" would be printed and // then would // be removed // from the queue System.out.println("remove and retrieve element, null if empty: " + queue.poll() + "\n"); // .peek() just returns the current element in the queue, null if empty // Here it will print "its own" as "has" is removed above. System.out.println("retrieve element, null if empty: " + queue.peek() + "\n"); } }