We need to write a safe enqueue() method that will fail when the queue is full.
Steps for completion:
- Modify the enqueue and dequeue methods shown in the preceding code so that the enqueue returns a Boolean value which is false when the queue is full and cannot accept further elements.
- Implement the method signatures as follows:
public boolean enqueueSafe(V item)
public Optional<V> dequeueSafe()
- The following Snippet 2.26 provides an implementation of the enqueueSafe() method, returning a Boolean value when the queue is full:
private boolean full = false;
public boolean enqueueSafe(V item) {
if (!full) {
array[tailPtr] = item;
tailPtr = (tailPtr + 1) % array.length;
this.full = tailPtr == headPtr;
return true;
}
return false;
}
Snippet 2.26: Safe Enqueue and dequeue solution. Source class name: QueueArray
We have seen how both queues and stacks can be implemented using a static array structure instead of using the dynamic linked list. This has the advantage of consuming less memory per element as a linked list has to store pointers to other nodes. However, this comes at the cost of having a limit on the structure size.