java 如何在java中的Queue前面添加一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25399933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add an element in front of Queue in java?
提问by novice
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
我正在使用Queue<T> q1
并且我知道将q1.offer();
在队列末尾添加一个元素。但是现在,我想做的是在队列前面添加一个元素,这是Queue 所不能实现的。我能想到的可能方法是
- 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.
- 使用双端队列,我可以在前面和最后添加元素。
- 反转 q1,在队列末尾添加元素并再次反转。
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.
我在 1) 中遇到的问题是将现有 Queue 转换为 Deque,反之亦然;并在 2) 如何使用Collections.reverseOrder();
来反转现有的队列。
回答by SureshBonam
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...
以下是在集合中使用 deque 和 asLifoQueue 方法将元素添加到队列的第一个元素的方法。这将排列元素的最后顺序...
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);
}
}
}
回答by Gabriel Negut
If you have to insert an element at the front, a Queue
is definitely not the solution. Go for a double ended queue
.
如果非要在前面插入一个元素,aQueue
绝对不是办法。去一个double ended queue
。
回答by Renat Bekbolatov
If you use "Queue q1" - that is only a declaration of variable q1, while Queueitself is only an interface. Are you probably looking to work with some implementation of Queue?
如果您使用 "Queue q1" - 那只是变量q1的声明,而Queue本身只是一个接口。您可能希望使用 Queue 的某些实现吗?
Check out Java API: http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)
查看 Java API:http: //docs.oracle.com/javase/7/docs/api/java/util/Queue.html)