Reputation: 142
I'm trying to implement generic Queue based on Array
as data structure.
public class ArrayQueue<T>
{
public T Dequeue()
{
if (Queue[Tail] == null)
return null;
T value = Queue[Tail];
Queue[Tail] = null;
Tail--;
if (Tail - Head < Queue.Length / (ResizeCoefficient * 2))
ResizeQueue(Queue.Length / ResizeCoefficient);
return value;
}
...
private T[] Queue;
}
As you can see, I'm using null as "empty" cell and not default(T)
.
That's because if T is int, default(int) = 0
and 0 can be valid input, not empty value. So T must be reference type or Nullable
. But i don't want client to bother about it, class should support both ArrayQueue<int>
and ArrayQueue<Product>
.
Can you suggest any solution with generic class without constrains and in the same time being able to have Array
of type that can be null
?
Upvotes: 0
Views: 122
Reputation: 12954
The value null
should also be a valid value inside your queue. It should not be used to keep track of your tail.
Try to implement a counter or an index which can tell you how many elements are in the queue or where the tail ends. Using this you can insert and return ANY value, including null
, 0
, default(T)
, etc.
Maybe a good idea to look at the code of the System.Collections.Generic.Queue.
Upvotes: 2