I am planning to implement a bounded queue without using the Queue<T> class. After reading pros and cons of Arrays and LinkedList<T>, I am leaning more towards using Array to implement queue functionality. The collection will be fixed size. I just want to add and remove items from the queue.
something like
public class BoundedQueue<T>
{
private T[] queue;
int queueSize;
public BoundedQueue(int size)
{
this.queueSize = size;
queue = new T[size + 1];
}
}
instead of
public class BoundedQueue<T>
{
private LinkedList<T> queue;
int queueSize;
public BoundedQueue(int size)
{
this.queueSize = size;
queue = new LinkedList<T>();
}
}
I have selected Array because of efficiency and due to the fact that collection is fixed size. Would like to get other opinions on this. Thanks.
You should of course use a
Queue<T>, but in the question you said that you don’t want to use queue and instead implement the queue yourself. You need to consider first your use case for this class. If you want to implement something quickly you can use aLinkedList<T>but for a general purpose library you would want something faster.You can see how it is implemented in .NET by using .NET Reflector. These are the fields it has:
As you can see it uses an array. It is also quite complicated with many fields concerned with how the array should be resized. Even if you are implementing a bounded array you would want to allow that the array can be larger than the capacity to avoid constantly moving items in memory.
Regarding thread safety, neither type offers any guarantees. For example in the documentation for
LinkedList<T>it says this: