3

I am using Queue<T> q1 and I know that an element will be added using q1.offer(); 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 Collections.reverseOrder(); to reverse the existing Queue.

novice
  • 800
  • 2
  • 11
  • 25
  • If your requirements are satisfied by data structure X, why the heck use data structure Y? – Smutje Aug 20 '14 at 08:26
  • You could use priority Queue. http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue – diginoise Aug 20 '14 at 08:27

3 Answers3

7

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>();

    dd.offerFirst(123);

    dd.offerFirst(258);

    dd.offerFirst(125);

    System.out.println(dd);

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

    System.out.println(q1);

}

}

SureshBonam
  • 196
  • 1
  • 4
1

If you have to insert an element at the front, a Queue is definitely not the solution. Go for a double ended queue.

Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
1

If you use "Queue q1" - that is only a declaration of variable q1, while Queue itself is only an interface. Are you probably looking to work with some implementation of Queue?

Check out Java API: http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)

Renat Bekbolatov
  • 329
  • 4
  • 11