java使用迭代器从循环队列中的一个位置获取项 1 年,1 月 Questions & Answers 393 我有一个循环队列,但我不知道如何从某个位置获取某个项目,标题应该是:public E peek(int index),并使用通用迭代器
# 1 楼答案 正如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 希望这有帮助
# 1 楼答案
正如Nilesh指出的,队列不打算与索引一起使用。无论如何,您可以使用队列和迭代器通过索引查找元素,通过自定义行为实现自己的类。如果是你寻找的例子,请考虑下面的例子:
输出(如预期的那样):
希望这有帮助
# 2 楼答案
根据队列的设计,您不能这样做。您只能查看队列的标题
如果要按索引访问元素,请使用列表而不是队列