Queue two type
-PriorityQueue
-DeQueue
Methods of Queue Interface
-add(object) or offer(object) - add the elements
-remove() or poll() - remove the elements
-element() or peek() - it will retrive the top element
-size() - number of elements of queue
Example of Queue Java code..
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue preQueue = new PriorityQueue();
preQueue.add("A");
preQueue.add("B");
preQueue.add("C");
preQueue.add("D");
preQueue.add("E");
System.out.println("Head: "+preQueue.element());
System.out.println("Head: "+preQueue.peek());
Iterator i1 = preQueue.iterator();
while(i1.hasNext()){
System.out.println(i1.next());
}
System.out.println();
preQueue.remove();
preQueue.poll();
Iterator i2 = preQueue.iterator();
System.out.println("Aftering removing elements: ");
while(i2.hasNext()){
System.out.println(i2.next());
}
}
}
Exmple of Deque Java code..
import java.util.*;
public class DeQueueExample {
public static void main(String[] args) {
Deque deQueue = new ArrayDeque();
deQueue.add("A");
deQueue.add("B");
deQueue.add("C");
deQueue.add("D");
deQueue.add("E");
System.out.println("Initial size of Deque: "+deQueue.size());
//get value and does not remove the elements form Deque
System.out.println("Deque peek: "+deQueue.peek());
//get first value and remove that object form Deque
System.out.println("Deque poll: "+deQueue.poll());
System.out.println("Final size of Deque: "+deQueue.size());
}
}
No comments:
Post a Comment