The last of the queues is a LIFO queue. This queue behaves like a stack. It follows LIFO ordering.
public static void main(final String[] args) { final Deque<Integer> deQ = new ArrayDeque<Integer>(); final Queue<Integer> asLifoQ = Collections.asLifoQueue(deQ); asLifoQ.offer(4); asLifoQ.offer(5); asLifoQ.offer(6); System.out.println("LifoQueue Contents : " + asLifoQ); // should behave like a stack System.out.println(asLifoQ.poll()); System.out.println(asLifoQ.poll()); System.out.println(asLifoQ.poll()); }There is no direct way to create the same. We need to use the asLifoQueue method of Collections class to create a LIFO queue. Further this method requires an instance of Deque to be available . It will not work with any queue. The output is :
LifoQueue Contents : [6, 5, 4] 6 5 4Be sure to pass and empty Deque as the parameter. Any elements already present in the deque are not treated in the LIFO order.
No comments:
Post a Comment