Item
- the generic type of an item in this queuepublic class Queue<Item> extends Object implements Iterable<Item>
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 first item,
testing if the queue is empty, and iterating through
the items in FIFO order.
This implementation uses a singly linked list with a static nested class for
linked-list nodes. See LinkedQueue
for the version from the
textbook that uses a non-static nested class.
See ResizingArrayQueue
for a version that uses a resizing array.
The enqueue, dequeue, peek, size, and is-empty
operations all take constant time in the worst case.
For additional documentation, see Section 1.3 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
Constructor and Description |
---|
Queue()
Initializes an empty queue.
|
Modifier and Type | Method and Description |
---|---|
Item |
dequeue()
Removes and returns the item on this queue that was least recently added.
|
void |
enqueue(Item item)
Adds the item to this queue.
|
boolean |
isEmpty()
Returns true if this queue is empty.
|
Iterator<Item> |
iterator()
Returns an iterator that iterates over the items in this queue in FIFO order.
|
static void |
main(String[] args)
Unit tests the
Queue data type. |
Item |
peek()
Returns the item least recently added to this queue.
|
int |
size()
Returns the number of items in this queue.
|
String |
toString()
Returns a string representation of this queue.
|
public boolean isEmpty()
true
if this queue is empty; false
otherwisepublic int size()
public Item peek()
NoSuchElementException
- if this queue is emptypublic void enqueue(Item item)
item
- the item to addpublic Item dequeue()
NoSuchElementException
- if this queue is emptypublic String toString()
public Iterator<Item> iterator()
public static void main(String[] args)
Queue
data type.args
- the command-line arguments