Amit Amit - 2 years ago 171
Java Question

How to add an element in front of Queue in java?

I am using

Queue<T> q1
and I know that an element will be added using
at the end of the queue. But now, what I want to do is add an element in front of queue, which is not possible with Queue. The possible methods I could think of are

  • Use of double ended queue and I can add the elements in front and at the end.

  • reverse the q1, add the element at the end of the queue and reverse again.

Now, as a non-programmer guy, I am not sure, how to code these methods; which one is more economical and easier to do.

Problems I faced in 1) is transform of existing Queue to Deque and vice versa; and in 2) How to use
to reverse the existing Queue.

Answer Source

The following is the way to add elements to the first of queue using deque and asLifoQueue method in collections.this will arrange the elements in last in first out order...

    public class Practice15 {

public static void main(String[] args) {

    Deque<Integer> dd=new ArrayDeque<Integer>();





    Queue<Integer> q1=Collections.asLifoQueue(dd);




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download