Table of Contents
Queue Interface
The Queue Interface is part of the java.util package and extends the Collection interface. Queues are data structures that work in the FIFO (First In First Out) sequence. Queues are ordered lists and all elements are inserted at the end of the queue. The deletion of elements is done from the front of the queue.
Declaration
import java.util.*;
public interface Queue extends Collection
Queue Objects
Queue <Obj> queue = new PriorityQueue <obj>(); where obj defines the type of objects or elements contained in the queue.
Example
import java.util.LinkedList; import java.util.Queue; public class QueueDemo { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); //Adding elements for (int i=0; i<5; i++) q.add(i); System.out.println(“Elements of the Queue” + q); //removing an element int removable = q.remove(); System.out.println(“removed element” + removable); System.out.println(q); //To peek int head = q.peek(); System.out.println(“head of the queue” + head); int size = q.size(); System.out.println(“Size of the Queue” + size); } }
OUTPUT
Elements of the Queue [0, 1, 2, 3, 4]
removed element – 0
[1, 2, 3, 4]
head of the queue – 1
Size of the queue – 1
Deque Interface
Deque is the subtype of the queue interface. This is a type of queue that allows users to remove and add elements from both sides of the queue. Deques can serve both algorithms like FIFO (First In First Out) and LIFO (Last In First Out).
Declaration
public interface Deque extends Queue
Example
import java.util.*; public class DequeExample { public static void main(String[] args) { Deque<String> deque = new LinkedList<String>(); deque.add("Element 1 (Tail)"); deque.addFirst("Element 2 (Head)"); deque.addLast("Element 3 (Tail)"); deque.push("Element 4 (Head)"); deque.offer("Element 5 (Tail)"); deque.offerFirst("Element 6 (Head)"); System.out.println(deque + "\n"); deque.removeFirst(); deque.removeLast(); System.out.println("Deque after removing " + "first and last: " + deque); } }
0 Comments