Lets assume we are talking about a FIFO that will typically contain lots of elements.
An ArrayList is not a good choice, because removing the element at start of the list is an
O(N)
operation. (For a list with N elements)An LinkedList may not be a good choice, because getting the Nth element is an
O(N)
operation.
I think you need a circular buffer backed by an array. This will give you O(1)
FIFO insertion, O(1)
FIFO removal, and O(1)
indexed get
of the element i
from the FIFO start. The circular buffer behaviour is inplemented using two index, one for the position of the start of the queue, and one for the position of the end. Insertion and removal just involve moving one or other of the indexes, and get(i)
boils down to a fetch of backingArray[(startPos + i) % backingArray.length]
with some error checking.
If you need the FIFO to be expandable, you can implement this by doubling the size of the backing array ... and still get amortized O(1)
for insertion, removal and indexing.
I think that the Apache Commons CircularFifoQueue
class matches your requirements for the fixed sized FIFO case. It includes a get(i)
method for getting the ith element.