如何从队列中获取特定元素? [英] How to get a particular element from Queue?
本文介绍了如何从队列中获取特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与 ArrayList
不同,在 Queue <中没有
get(int index)
方法。 / code>来检索指定位置的元素。
Unlike ArrayList
, there is no get(int index)
method in Queue
to retrieve the element at specified position.
任何人请告诉我如何在 Queue $ c $中实现此操作c>?
Anybody please tell me how to achieve this in Queue
?
谢谢。
推荐答案
您可以从中删除元素排队直到到达所需的队列。您可以在队列末尾重新添加已删除的元素,或将它们放入其他队列(并在到达所需元素后添加其余元素)。
You can remove elements from the Queue until you reach the needed one. You can re-add the removed elements at the end of the queue or put them in a different queue (and add the rest after you reached the needed element).
您
public static <T> T get(Queue<T> queue, int index) {
synchronized (queue) {
if (queue == null) {
return null;
}
int size = queue.size();
if (index < 0 || size < index + 1) {
return null;
}
T element = null;
for (int i = 0; i < size; i++) {
if (i == index) {
element = queue.remove();
} else {
queue.add(queue.remove());
}
}
return element;
}
}
这篇关于如何从队列中获取特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文