When to use queue over arraylist

arraylist, java, queue

Solution

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.

Take the following code as an example:

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

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.

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.

Problem

One basic argument to use a Queue over an ArrayList is that Queue guarantees FIFO behavior. 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. What is so special about Queue as compared to traditional ArrayList?

Original source