有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 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
    

    希望这有帮助

  2. # 2 楼答案

    根据队列的设计,您不能这样做。您只能查看队列的标题

    如果要按索引访问元素,请使用列表而不是队列