

Pretty easy to grasp if you followed along in the last section. Next, we'll define the isEmpty and isFull functionalities. Like we saw in the images from the previous section, we have set the initial index of the front and back to -1. We are using 3 as the maximum number of items that can be enqueued in the array. We have created our variables and their parameters. We will break this section down by creating each operation and then putting everything together at the end. Time for some code! Queue Implementation in Java When this happens, we will reset their index to -1 (their initial starting point). If we dequeue again at that point, the front arrow will move past the back arrow and then the queue will be considered empty because there is nothing there to delete. In the same order, if we keep removing items, it will get to a point where the front arrow meets the back arrow at the end of the queue. By removed, we do not mean from the array but from the queue – only items from the front position to the back position are part of the queue. This implies that the item at index 0 has been removed. Now the front arrow has moved to index 1.

If we execute it again then it will move to the next number which is 10 and continue in that order for as long as we call it. Remember the first-come-first-out sequence? When we execute the dequeue operation, it will first remove 5 from the queue. So the back arrow followed the items in the order they were added all the way to the last. We will go on and fill up the array so we can see what happens when we dequeue. But now that we have enqueued more items, the back will keep following the last item. Since that was the first and only item then, the front and back sat at that position. The front and back moved together in the last example so that the front could assume the position of the first item. This will continue as we enqueue more items. Next, we will see what happens as we enqueue more itemsĪ second item has been added but only the back moved. The position of the front and back have moved as well. We have inserted (enqueued) our first item – 5. Let us add some items into our array and see what happens. When both positions are at -1, it means the array is empty. The arrows show the position of the front and back of our array. This will enable us move the front and back position properly as values are added. While implementing our code, we are going to set the index of the front and back values of our array to -1. The indices of arrays in most programming languages start from 0.


#Java queue vs deque how to#
