我有一个圆形队列,但是我不知道如何从某个位置获得某个项目,标题将是: public e peeki(int index(并使用通用迭代器。
正如尼尔什(Nilesh(指出的那样,队列不打算与索引一起使用。无论如何,您可以使用队列和迭代器使用自定义行为来实现自己的类,以通过索引找到一个元素。如果是这样的情况,请考虑以下示例:
public class QueueExample<E> {
private Queue<E> queue = new LinkedList<>();
public void add(E item) {
queue.add(item);
}
public E peek(int index) {
E item = null;
Iterator<E> iterator = queue.iterator();
while (iterator.hasNext()) {
E temp = iterator.next();
if (index-- == 0) {
item = temp;
break;
}
}
return item;
}
public static void main(String[] args) {
QueueExample<String> queueExample = new QueueExample<>();
queueExample.add("One");
queueExample.add("Two");
queueExample.add("Three");
System.out.println(queueExample.peek(0));
System.out.println(queueExample.peek(2));
System.out.println(queueExample.peek(1));
System.out.println(queueExample.peek(4));
}
}
输出(如预期(:
One
Three
Two
null
希望这会有所帮助。
通过队列设计,您不能做到这一点。您只能窥视队列的标题。
如果要通过索引访问元素,请使用列表而不是队列。