In Java, the LinkedList
class implements the Queue
interface. Which means it works as a queue. If you use .add()
you will put things at the end of the list (queue), and if you use .remove()
, you will pull things from the head of the list (queue).
Retrieval from an ArrayList
is O(1), but removal is not. Consider the following:
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(3);
Your list al
is now {1, 2, 3}
.
Now you do: al.remove(0)
After that, al
is {2, 3}
. But for this to happen, once you removed the head of the list, all other objects after the head needed to shift down one unit. So it was actually O(n). Removal is only O(1) if you are removing the tail. But you need to be removing the head each time.