Class Queue<Item>

  • Type Parameters:
    Item - the generic type of each item in this queue
    All Implemented Interfaces:
    Iterable<Item>

    public class Queue<Item>
    extends Object
    implements Iterable<Item>
    The Queue class represents a first-in-first-out (FIFO) queue of generic items. It supports the usual enqueue and dequeue operations, along with methods for peeking at the top item, testing if the queue is empty, getting the number of items in the queue, and iterating over the items in FIFO order.

    This implementation uses a singly-linked list with a nested class for linked-list nodes. The enqueue, dequeue, peek, size, and is-empty operations all take constant time in the worst case.

    For additional documentation, see Section 4.3 of Computer Science: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne.

    Author:
    Robert Sedgewick, Kevin Wayne
    • Constructor Detail

      • Queue

        public Queue()
        Initializes an empty queue.
    • Method Detail

      • isEmpty

        public boolean isEmpty()
        Returns true if this queue is empty.
        Returns:
        true if this queue is empty; false otherwise
      • size

        public int size()
        Returns the number of items in this queue.
        Returns:
        the number of items in this queue
      • length

        public int length()
        Returns the number of items in this queue.
        Returns:
        the number of items in this queue
      • peek

        public Item peek()
        Returns the item least recently added to this queue.
        Returns:
        the item least recently added to this queue
        Throws:
        NoSuchElementException - if this queue is empty
      • enqueue

        public void enqueue​(Item item)
        Add the item to the queue.
        Parameters:
        item - the item to enqueue
      • dequeue

        public Item dequeue()
        Removes and returns the item on this queue that was least recently added.
        Returns:
        the item on this queue that was least recently added
        Throws:
        NoSuchElementException - if this queue is empty
      • toString

        public String toString()
        Returns a string representation of this queue.
        Overrides:
        toString in class Object
        Returns:
        the sequence of items in FIFO order, separated by spaces
      • iterator

        public Iterator<Item> iterator()
        Returns an iterator that iterates over the items in this queue in FIFO order.
        Specified by:
        iterator in interface Iterable<Item>
        Returns:
        an iterator that iterates over the items in this queue in FIFO order
      • main

        public static void main​(String[] args)
        Unit tests the Queue data type.
        Parameters:
        args - the command-line arguments