何时在数组列表上使用队列 [英] When to use queue over arraylist

查看:20
本文介绍了何时在数组列表上使用队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ArrayList 上使用 Queue 的一个基本参数是 Queue 保证 FIFO 行为.

One basic argument to use a Queue over an ArrayList is that Queue guarantees FIFO behavior.

但是如果我向 ArrayList 添加 10 个元素,然后从第 0 个元素开始迭代这些元素,那么我将按照添加元素的相同顺序检索这些元素.从本质上讲,这保证了 FIFO 行为.

But if I add 10 elements to an ArrayList and then iterate over the elements starting from the 0th element, then I will retrieve the elements in the same order as they were added. So essentially, that guarantees a FIFO behavior.

与传统的 ArrayList 相比,Queue 有什么特别之处?

What is so special about Queue as compared to traditional ArrayList?

推荐答案

如果我给你一个 Queue 实例,那么你就会知道通过迭代调用 remove() 你将按 FIFO 顺序检索元素.如果我给了你一个 ArrayList 实例,那么你就不能做出这样的保证.

If I gave you a Queue instance then you would know that by iteratively calling remove() you would retrieve the elements in FIFO order. If i gave you an ArrayList instance then you can make no such guarantee.

以下代码为例:

        ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(5);
    list.add(4);
    list.add(3);
    list.add(2);
    list.add(1);


    list.set(4,5);
    list.set(3,4);
    list.set(2,3);
    list.set(1,2);
    list.set(0,1);

    System.out.println(list);

如果我现在给你这个列表,那么我从 0 到 4 的迭代你不会得到按 FIFO 顺序的元素.

If I were now to give you this list, then my iterating from 0 to 4 you would not get the elements in FIFO order.

另外,我想说另一个区别是抽象.使用 Queue 实例,您不必担心索引,如果您不需要 ArrayList 必须提供的所有内容,这会使事情更容易考虑.

Also, I would say another difference is abstraction. With a Queue instance you don't have to worry about indexes and this makes things easier to think about if you don't need everything ArrayList has to offer.

这篇关于何时在数组列表上使用队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆