0

我有一个循环队列,但我不知道如何从某个位置获取某个项目,标题将是:public E peeki(int index)并使用通用迭代器。

4

2 回答 2

0

As Nilesh pointed out, Queue is not intended to be used with indexes. Anyway, you may implement your own class with custom behaviour using Queue and iterator to find an element by index. If it is the case your looking for, please, consider the following example:

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));
    }
}

The output (as expected):

One
Three
Two
null

Hope this helps.

于 2017-05-01T20:55:54.760 回答
0

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

如果要按索引访问元素,请使用 List 而不是 Queue。

于 2017-05-01T20:25:57.537 回答