I'm trying to figure out subtle difference in implementation of static nested class vs inner class (non-static nested class). For example, on http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Queue.java.html, you can find the following code:
public class Queue<Item> implements Iterable<Item> {
private Node<Item> first; // beginning of queue
private Node<Item> last; // end of queue
private int N; // number of elements on queue
// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
...
/**
* Returns an iterator that iterates over the items in this queue in FIFO order.
*
* @return an iterator that iterates over the items in this queue in FIFO order
*/
public Iterator<Item> iterator() {
return new ListIterator<Item>(first); //why parameter needed?
}
// an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current; //why not current = first?
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
...
I wonder why you have to pass the variable first via the constructor of ListIterator? Why can't I just use private Node<Item> current = first; at declaration. I know that if I have used inner class for Node, I can directly assign first to current (like in http://algs4.cs.princeton.edu/13stacks/LinkedQueue.java.html).