如何获取元素在队列中的位置

时间:2018-08-01 10:12:48

标签: java queue

例如,是否有一种简单的方法来获取元素在队列中的当前位置:

我当前的队列是[1,0,5,4,7,8,6]

我想知道4在这个队列中的位置,在这个例子中,它的3,有没有办法用java队列来实现呢?

4 个答案:

答案 0 :(得分:1)

队列可能不是最好的解决方案,因为它不存储索引。 但是,队列实现Iterable使得您可以遍历该结构:

    Queue<Integer> queue = new LinkedList<>();

    queue.add(1);
    queue.add(0);
    queue.add(5);
    queue.add(4);
    queue.add(7);
    queue.add(8);
    queue.add(6);

    int lookingFor = 0;

    int counter = 0;
    for (Integer number : queue) {
        if (number == lookingFor) {
            System.out.println(lookingFor + " is at position " + counter + " in the queue.");
            break;
        }
        else counter++;
    }

这将输出以下内容:

0 is at position 1 in the queue.

请注意,这只会找到第一个出现的0。

答案 1 :(得分:0)

它支持FIFO,而size()您无法获得它的索引。您必须计算堆上的删除操作。

答案 2 :(得分:0)

您已经知道queue是一个集合,它通过添加(最后一个)和轮询(从头开始/从头开始)来给我们FIFO

这也意味着不能保证可以使用它在队列中找到其index/position

如果您确实需要类似的东西,可以尝试使用add(E e)remove(0)indexOf(Object o)来达到List的相同效果:

public static void main(String... args) {
    List<Integer> list = new ArrayList<>();
    int[] arr = new int[]{1,0,5,4,7,8,6};
    for (int a : arr) {
        list.add(a);
    }
    System.out.println("After adding: " + list);
    System.out.println(list.indexOf(4));
    System.out.print("Popping out now: ");
    while(!list.isEmpty()) {
        System.out.print(list.remove(0) + " ");
    }
}

结果将是:

After adding: [1, 0, 5, 4, 7, 8, 6]
3 // you can find the index easily;
Popping out now: 1 0 5 4 7 8 6 // still FIFO;

答案 3 :(得分:0)

Queue的默认接口对此没有任何方法。如果您需要此功能,我认为您必须使用内部的索引集合来创建自己的接口实现。