Queue is a generic interface which extends
Collection interface. Queue is used to store the elements in FIFO(First In First Out) manner.
Declaration
interface Queue<<E>>
Queue
interface have the following methods.
The classes which implement the Queue interface are
AbstractQueue
,
ArrayBlockingQueue
,
ArrayDeque
,
ConcurrentLinkedDeque
,
ConcurrentLinkedQueue
,
DelayQueue
,
LinkedBlockingDeque
,
LinkedBlockingQueue
,
LinkedList
,
LinkedTransferQueue
,
PriorityBlockingQueue
,
PriorityQueue
,
SynchronousQueue
QueueDemo
class QueueDemo
{
public static void main(String arg[])
{
Queue<Integer> abq = new ArrayBlockingQueue<Integer>(3);
abq.add(1);
abq.add(2);
abq.add(3);
System.out.println("Till now we have added 3 numbers");
System.out.println("Now adding fourth element violating queue behaviour");
System.out.println("Added fourth element : " + abq.offer(4)); // LINE A
System.out.println("Elements in ArrayBlockingQueue : " + abq);
abq.clear(); // Clears the elements in Queue // LINE B
System.out.println("Remove first element : " + abq.poll()); // LINE C
}
}
OUTPUTTill now we have added 3 numbers
Now adding fourth element violating queue behaviour
Added fourth element : false
Elements in ArrayBlockingQueue : [1, 2, 3]
Remove first element : null
DESCRIPTIONIn the above program we have created a ArrayBlockingQueue
with the reference abq
and restricted its capacityt to 3
and added three elements later at LINE A
we tried to add fourth element using offer
method which returned false
since the capacity is restricted. At LINE B
we have cleared the elements in the queue using clear
method and tried to reomve the first element using poll
method in the queue which returned false
since the queue is empty