3. Bags, Queues, and Stacks Flashcards

1
Q

Generics

A

An essential characteristic of collection ADTs is that we should be able to use them for any type of data. A specific Java mechanism known as generics enables this capability. The notation <Item> after the class name in each of our APIs defines the name Item as a type parameter, a symbolic placeholder for some concrete type to be used by the client. You can read Stack<Item> as "stack of items." For example, you can write code such as</Item></Item>

Stack<String> stack = new Stack<String>();
stack.push("Test");
...
String next = stack.pop();</String></String>

to use a stack for String objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Autoboxing

A

Type parameters have to be instantiated as reference types, so Java automatically converts between a primitive type and its corresponding wrapper type in assignments, method arguments, and arithmetic/logic expressions. This conversion enables us to use generics with primitive types, as in the following code:

Stack<Integer> stack = new Stack<Integer>();
stack.push(17); // autoboxing (int -> Integer)
int i = stack.pop(); // unboxing (Integer -> int)</Integer></Integer>

Automatically casting a primitive type to a wrapper type is known as autoboxing, and automatically casting a wrapper type to a primitive type is known as unboxing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Iterable collections:

A

For many applications, the client’s requirement is just to process each of the items in some way, or to iterate through the items in the collection. Java’s foreach statement supports this paradigm. For example, suppose that collection is a Queue<Transaction>. Then, if the collection is iterable, the client can print a transaction list with a single statement:</Transaction>

for (Transaction t : collection)
StdOut.println(t);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Bags

A

A bag is a collection where removing items is not supported—its purpose is to provide clients with the ability to collect items and then to iterate through the collected items.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

//Stats.java is a bag client that reads a sequence of real numbers from standard input and prints out their mean and standard deviation.

public class Stats {

A

public class Stats {
public static void main(String[] args) {

    // read in numbers
    Bag<Double> numbers = new Bag<Double>();
    while (!StdIn.isEmpty()) {
        numbers.add(StdIn.readDouble());
    }
    int n = numbers.size();

    // compute sample mean
    double sum = 0.0;
    for (double x : numbers)
        sum += x;
    double mean = sum/n;

    // compute sample standard deviation
    sum = 0.0;
    for (double x : numbers) {
        sum += (x - mean) * (x - mean);
    }
    double stddev = Math.sqrt(sum/(n-1));

    StdOut.printf("Mean:    %.2f\n", mean);
    StdOut.printf("Std dev: %.2f\n", stddev);
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

FIFO queues.

A

A FIFO queue is a collection that is based on the first-in-first-out (FIFO) policy. The policy of doing tasks in the same order that they arrive is one that we encounter frequently in everyday life: from people waiting in line at a theater, to cars waiting in line at a toll booth, to tasks waiting to be serviced by an application on your computer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Pushdown stack

A

A pushdown stack is a collection that is based on the last-in-first-out (LIFO) policy. When you click a hyperlink, your browser displays the new page (and pushes onto a stack). You can keep clicking on hyperlinks to visit new pages, but you can always revisit the previous page by clicking the back button (popping it from the stack).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

//Reverse.java is a stack client that reads a sequence of integers from standard input and prints them in reverse order.

A

public class Reverse {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
while (!StdIn.isEmpty()) {
stack.push(StdIn.readInt());
}
for (int i : stack) {
StdOut.println(i);
}
}
}</Integer></Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Arithmetic expression evaluation

A

Evaluate.java is a stack client that evaluates fully parenthesized arithmetic expressions. It uses Dijkstra’s 2-stack algorithm:
Push operands onto the operand stack.
Push operators onto the operator stack.
Ignore left parentheses.
On encountering a right parenthesis, pop an operator, pop the requisite number of operands, and push onto the operand stack the result of applying that operator to those operands.
This code is a simple example of an interpreter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Evaluate.java

A

public class Evaluate {
public static void main(String[] args) {
Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>();</Double></Double></String></String>

    while (!StdIn.isEmpty()) {
        String s = StdIn.readString();
        if      (s.equals("("))               ;
        else if (s.equals("+"))    ops.push(s);
        else if (s.equals("-"))    ops.push(s);
        else if (s.equals("*"))    ops.push(s);
        else if (s.equals("/"))    ops.push(s);
        else if (s.equals("sqrt")) ops.push(s);
        else if (s.equals(")")) {
            String op = ops.pop();
            double v = vals.pop();
            if      (op.equals("+"))    v = vals.pop() + v;
            else if (op.equals("-"))    v = vals.pop() - v;
            else if (op.equals("*"))    v = vals.pop() * v;
            else if (op.equals("/"))    v = vals.pop() / v;
            else if (op.equals("sqrt")) v = Math.sqrt(v);
            vals.push(v);
        }
        else vals.push(Double.parseDouble(s));
    }
    StdOut.println(vals.pop());
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Fixed-capacity stack of strings

A

FixedCapacityStackOfString.java implements a fixed-capacity stack of strings using an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

//FixedCapacityStackOfStrings.java
import java.util.Iterator;
import java.util.NoSuchElementException;

public class FixedCapacityStackOfStrings implements Iterable<String> {</String>

A

private String[] a; // holds the items
private int n; // number of items in stack

// create an empty stack with given capacity
public FixedCapacityStackOfStrings(int capacity) {
    a = new String[capacity];
    n = 0;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

//FixedCapacityStackOfStrings.java
public boolean isEmpty() {

A

return n == 0;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

//FixedCapacityStackOfStrings.java
public boolean isFull() {

A

return n == a.length;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

//FixedCapacityStackOfStrings.java
public void push(String item) {

A

a[n++] = item;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

//FixedCapacityStackOfStrings.java
public String pop() {

A

return a[–n];
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

//FixedCapacityStackOfStrings.java
public String peek() {

A

return a[n-1];
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

//FixedCapacityStackOfStrings.java
public Iterator<String> iterator() {</String>

A

return new ReverseArrayIterator();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

//FixedCapacityStackOfStrings.java
// an array iterator, in reverse order
public class ReverseArrayIterator implements Iterator<String> {</String>

A

private int i = n-1;

    public boolean hasNext() {
        return i >= 0;
    }

    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        return a[i--];
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

//FixedCapacityStackOfStrings.java
public static void main(String[] args) {

A

int max = Integer.parseInt(args[0]);
FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals(“-“)) stack.push(item);
else if (stack.isEmpty()) StdOut.println(“BAD INPUT”);
else StdOut.print(stack.pop() + “ “);
}
StdOut.println();

    // print what's left on the stack
    StdOut.print("Left on stack: ");
    for (String s : stack) {
        StdOut.print(s + " ");
    }
    StdOut.println();
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Fixed-capacity generic stack.

A

FixedCapacityStack.java implements a generic fixed-capacity stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

//FixedCapacityStack.java
import java.util.Iterator;
import java.util.NoSuchElementException;

public class FixedCapacityStack<Item> implements Iterable<Item> {</Item></Item>

A

private Item[] a; // holds the items
private int n; // number of items in stack

// create an empty stack with given capacity
public FixedCapacityStack(int capacity) {
    a = (Item[]) new Object[capacity];   // no generic array creation
    n = 0;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

//FixedCapacityStack.java
public boolean isEmpty() {

A

return n == 0;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

//FixedCapacityStack.java
public void push(Item item) {

A

a[n++] = item;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

//FixedCapacityStack.java
public Item pop() {

A

return a[–n];
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

//FixedCapacityStack.java
public Iterator<Item> iterator() {</Item>

A

return new ReverseArrayIterator();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

///FixedCapacityStack.java
/ an array iterator, in reverse order
public class ReverseArrayIterator implements Iterator<Item> {</Item>

A

private int i = n-1;

    public boolean hasNext() {
        return i >= 0;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

//FixedCapacityStack.java
public boolean hasNext() {

A

return i >= 0;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

//FixedCapacityStack.java
public Item next() {

A

if (!hasNext()) throw new NoSuchElementException();
return a[i–];
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

//FixedCapacityStack.java
public static void main(String[] args) {

A

int max = Integer.parseInt(args[0]);
FixedCapacityStack<String> stack = new FixedCapacityStack<String>(max);
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) stack.push(item);
else if (stack.isEmpty()) StdOut.println("BAD INPUT");
else StdOut.print(stack.pop() + " ");
}
StdOut.println();</String></String>

    // print what's left on the stack
    StdOut.print("Left on stack: ");
    for (String s : stack) {
        StdOut.print(s + " ");
    }
    StdOut.println();
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Array resizing stack

A

ResizingArrayStack.java implements a generic stack using a resizing array. With a resizing array, we dynamically adjust the size of the array so that it is both sufficiently large to hold all of the items and not so large as to waste an excessive amount of space. We double the size of the array in push() if it is full; we halve the size of the array in pop() if it is less than one-quarter full.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

//ResizingArrayStack.java
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code ResizingArrayStack} class represents a last-in-first-out (LIFO) stack
* of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a resizing array, which double the underlying array
* when it is full and halves the underlying array when it is one-quarter full.
* The <em>push</em> and <em>pop</em> operations take constant amortized time.
* The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
* constant time in the worst case.
*/
public class ResizingArrayStack<Item> implements Iterable<Item> {</Item></Item>

A

//ResizingArrayStack.java
// initial capacity of underlying resizing array
private static final int INIT_CAPACITY = 8;

private Item[] a;         // array of items
private int n;            // number of elements on stack

/**
 * Initializes an empty stack.
 */
public ResizingArrayStack() {
    a = (Item[]) new Object[INIT_CAPACITY];
    n = 0;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

//ResizingArrayStack.java
/**
* Is this stack empty?
*/
public boolean isEmpty() {

A

return n == 0;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

//ResizingArrayStack.java
/**
* Returns the number of items in the stack.
*/
public int size() {

A

return n;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

//ResizingArrayStack.java
// resize the underlying array holding the elements
private void resize(int capacity) {

A

assert capacity >= n;

    // textbook implementation
    Item[] copy = (Item[]) new Object[capacity];
    for (int i = 0; i < n; i++) {
        copy[i] = a[i];
    }
    a = copy;

   // alternative implementation
   // a = java.util.Arrays.copyOf(a, capacity);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

//ResizingArrayStack.java
/**
* Adds the item to this stack.
*/
public void push(Item item) {

A

if (n == a.length) resize(2*a.length); // double size of array if necessary
a[n++] = item; // add item
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

//ResizingArrayStack.java
/**
* Removes and returns the item most recently added to this stack.
*/
public Item pop() {

A

if (isEmpty()) throw new NoSuchElementException(“Stack underflow”);
Item item = a[n-1];
a[n-1] = null; // to avoid loitering
n–;
// shrink size of array if necessary
if (n > 0 && n == a.length/4) resize(a.length/2);
return item;
}

38
Q

//ResizingArrayStack.java
/**
* Returns (but does not remove) the item most recently added to this stack.
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*/
public Iterator<Item> iterator() {</Item>

A

return new ReverseArrayIterator();
}

// a array iterator, in reverse order
private class ReverseArrayIterator implements Iterator<Item> {
    private int i;

    public ReverseArrayIterator() {
        i = n-1;
    }

    public boolean hasNext() {
        return i >= 0;
    }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        return a[i--];
    }
}
39
Q

//ResizingArrayStack.java
/**
* Unit tests the {@code Stack} data type.
*
*/
public static void main(String[] args) {

A

ResizingArrayStack<String> stack = new ResizingArrayStack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) stack.push(item);
else if (!stack.isEmpty()) StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}</String></String>

40
Q

Array resizing queue.

A

ResizingArrayQueue.java implements the queue API with a resizing array.

41
Q

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code ResizingArrayQueue} class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a resizing array, which double the underlying array
* when it is full and halves the underlying array when it is one-quarter full.
* The <em>enqueue</em> and <em>dequeue</em> operations take constant amortized time.
* The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
* constant time in the worst case.
* <p>
*/
public class ResizingArrayQueue<Item> implements Iterable<Item> {</Item></Item>

A

// initial capacity of underlying resizing array
private static final int INIT_CAPACITY = 8;

private Item[] q;       // queue elements
private int n;          // number of elements on queue
private int first;      // index of first element of queue
private int last;       // index of next available slot
/**
 * Initializes an empty queue.
 */
public ResizingArrayQueue() {
    q = (Item[]) new Object[INIT_CAPACITY];
    n = 0;
    first = 0;
    last = 0;
}
42
Q

/**
* Is this queue empty?
* @return true if this queue is empty; false otherwise
*/
public boolean isEmpty() {

A

public boolean isEmpty() {
return n == 0;
}

43
Q

/**
* Returns the number of items in this queue.
* @return the number of items in this queue
*/
public int size() {

A

return n;
}

44
Q

// resize the underlying array
private void resize(int capacity) {

A

assert capacity >= n;
Item[] copy = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
copy[i] = q[(first + i) % q.length];
}
q = copy;
first = 0;
last = n;
}

45
Q
  • Adds the item to this queue.
    • @param item the item to add
      */
      public void enqueue(Item item) {
A

// double size of array if necessary and recopy to front of array
if (n == q.length) resize(2*q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
n++;
}

46
Q

/**
* Removes and returns the item on this queue that was least recently added.
* @return the item on this queue that was least recently added
* @throws java.util.NoSuchElementException if this queue is empty
*/
public Item dequeue() {

A

if (isEmpty()) throw new NoSuchElementException(“Queue underflow”);
Item item = q[first];
q[first] = null; // to avoid loitering
n–;
first++;
if (first == q.length) first = 0; // wrap-around
// shrink size of array if necessary
if (n > 0 && n == q.length/4) resize(q.length/2);
return item;
}

47
Q
  • Returns the item least recently added to this queue.
    • @return the item least recently added to this queue
    • @throws java.util.NoSuchElementException if this queue is empty
      */
      public Item peek() {
A

if (isEmpty()) throw new NoSuchElementException(“Queue underflow”);
return q[first];
}

48
Q

/**
* 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() {</Item>

A

return new ArrayIterator();
}

49
Q

// an array iterator, from first to last-1
private class ArrayIterator implements Iterator<Item> {
private int i = 0;</Item>

    public boolean hasNext() {
        return i < n;
    }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = q[(i + first) % q.length];
        i++;
        return item;
    }
A

private int i = 0;

    public boolean hasNext() {
        return i < n;
    }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = q[(i + first) % q.length];
        i++;
        return item;
    }
}
50
Q
  • Unit tests the {@code ResizingArrayQueue} data type.
    *
    • @param args the command-line arguments
      */
      public static void main(String[] args) {
A

ResizingArrayQueue<String> queue = new ResizingArrayQueue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) queue.enqueue(item);
else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}</String></String>

}

51
Q

Linked lists

A

A linked list is a recursive data structure that is either empty (null) or a reference to a node having a generic item and a reference to a linked list. To implement a linked list, we start with a nested class that defines the node abstraction
private class Node {
Item item;
Node next;
}

52
Q

Building a linked list

A

o build a linked list that contains the items to, be, and or, we create a Node for each item, set the item field in each of the nodes to the desired value, and set the next fields to build the linked list.

53
Q

Insert at the beginning.

A

The easiest place to insert a new node in a linked list is at the beginning.

54
Q

Remove from the beginning

A

Removing the first node in a linked list is also easy.

55
Q

Insert at the end.

A

To insert a node at the end of a linked list, we maintain a link to the last node in the list.

56
Q

Traversal

A

The following is the idiom for traversing the nodes in a linked list.

for (Node x = first; x != null; x = x.next) {
// process x.item
}

57
Q

Linked list implementation of a stack

A

Stack.java implements a generic stack using a linked list. It maintains the stack as a linked list, with the top of the stack at the beginning, referenced by an instance variable first. To push() an item, we add it to the beginning of the list; to pop() an item, we remove it from the beginning of the list.

58
Q

//Stack.java
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a singly linked list with a static nested class for
* linked-list nodes. See {@link LinkedStack} for the version from the
* textbook that uses a non-static nested class.
* See {@link ResizingArrayStack} for a version that uses a resizing array.
* The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
*/
public class Stack<Item> implements Iterable<Item> {</Item></Item>

A

private Node<Item> first; // top of stack
private int n; // size of the stack</Item>

// helper linked list class
private static class Node<Item> {
    private Item item;
    private Node<Item> next;
}

/**
 * Initializes an empty stack.
 */
public Stack() {
    first = null;
    n = 0;
}
59
Q

//Stack.java
/**
* Returns true if this stack is empty.
*
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {

A

return first == null;
}

60
Q

//Stack.java
/**
* Returns the number of items in this stack.
*
* @return the number of items in this stack
*/
public int size() {

A

return n;
}

61
Q

//Stack.java
/**
* Adds the item to this stack.
*
* @param item the item to add
*/
public void push(Item item) {

A

Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}</Item></Item>

62
Q

//Stack.java
/**
* Removes and returns the item most recently added to this stack.
*
* @return the item most recently added
* @throws NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException(“Stack underflow”);
Item item = first.item; // save item to return
first = first.next; // delete first node
n–;
return item; // return the saved item

A

if (isEmpty()) throw new NoSuchElementException(“Stack underflow”);
Item item = first.item; // save item to return
first = first.next; // delete first node
n–;
return item; // return the saved item
}

63
Q

//Stack.java
/**
* Returns (but does not remove) the item most recently added to this stack.
*
* @return the item most recently added to this stack
* @throws NoSuchElementException if this stack is empty
*/
public Item peek() {

A

if (isEmpty()) throw new NoSuchElementException(“Stack underflow”);
return first.item;
}

64
Q

//Stack.java
* Returns a string representation of this stack.
*
* @return the sequence of items in this stack in LIFO order, separated by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(‘ ‘);
}
return s.toString();
}

A

StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(‘ ‘);
}
return s.toString();
}

65
Q

//Stack.java
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
*
* @return an iterator to this stack that iterates through the items in LIFO order
*/
public Iterator<Item> iterator() {
return new LinkedIterator(first);
}</Item>

// the iterator
private class LinkedIterator implements Iterator<Item> {
    private Node<Item> current;

    public LinkedIterator(Node<Item> first) {
        current = first;
    }

    // is there a next item?
    public boolean hasNext() {
        return current != null;
    }

    // returns the next item
    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = current.item;
        current = current.next;
        return item;
    }
}
A

return new LinkedIterator(first);
}

// the iterator
private class LinkedIterator implements Iterator<Item> {
    private Node<Item> current;

    public LinkedIterator(Node<Item> first) {
        current = first;
    }

    // is there a next item?
    public boolean hasNext() {
        return current != null;
    }

    // returns the next item
    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = current.item;
        current = current.next;
        return item;
    }
}
66
Q

//Stack.java
/**
* Unit tests the {@code Stack} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
stack.push(item);
else if (!stack.isEmpty())
StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}</String></String>

A

Stack<String> stack = new Stack<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
stack.push(item);
else if (!stack.isEmpty())
StdOut.print(stack.pop() + " ");
}
StdOut.println("(" + stack.size() + " left on stack)");
}
}</String></String>

67
Q

Linked list implementation of a queue.

A

Program Queue.java implements a generic FIFO queue using a linked list. It maintains the queue as a linked list in order from least recently to most recently added items, with the beginning of the queue referenced by an instance variable first and the end of the queue referenced by an instance variable last. To enqueue() an item, we add it to the end of the list; to dequeue() an item, we remove it from the beginning of the list.

68
Q

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* The {@code Queue} class represents a first-in-first-out (FIFO)
* queue of generic items.
* It supports the usual <em>enqueue</em> and <em>dequeue</em>
* operations, along with methods for peeking at the first item,
* testing if the queue is empty, and iterating through
* the items in FIFO order.
* <p>
* This implementation uses a singly linked list with a static nested class for
* linked-list nodes. See {@link LinkedQueue} for the version from the
* textbook that uses a non-static nested class.
* See {@link ResizingArrayQueue} for a version that uses a resizing array.
* The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
* operations all take constant time in the worst case.
* <p>
*/
public class Queue<Item> implements Iterable<Item> {</Item></Item>

A

private Node<Item> first; // beginning of queue
private Node<Item> last; // end of queue
private int n; // number of elements on queue</Item></Item>

// helper linked list class
private static class Node<Item> {
    private Item item;
    private Node<Item> next;
}

/**
 * Initializes an empty queue.
 */
public Queue() {
    first = null;
    last  = null;
    n = 0;
}
69
Q

/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code false} otherwise
*/
public boolean isEmpty() {

A

return first == null;
}

70
Q

/**
* Returns the number of items in this queue.
*
* @return the number of items in this queue
*/
public int size() {

A

return n;
}

71
Q

/**
* Returns the item least recently added to this queue.
*
* @return the item least recently added to this queue
* @throws NoSuchElementException if this queue is empty
*/
public Item peek() {

A

if (isEmpty()) throw new NoSuchElementException(“Queue underflow”);
return first.item;
}

72
Q

/**
* Adds the item to this queue.
*
* @param item the item to add
*/
public void enqueue(Item item) {

A

Node<Item> oldlast = last;
last = new Node<Item>();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
n++;
}</Item></Item>

73
Q

/**
* Removes and returns the item on this queue that was least recently added.
*
* @return the item on this queue that was least recently added
* @throws NoSuchElementException if this queue is empty
*/
public Item dequeue() {

A

if (isEmpty()) throw new NoSuchElementException(“Queue underflow”);
Item item = first.item;
first = first.next;
n–;
if (isEmpty()) last = null; // to avoid loitering
return item;
}

74
Q
  • Returns a string representation of this queue.
    *
    • @return the sequence of items in FIFO order, separated by spaces
      */
      public String toString() {
A

StringBuilder s = new StringBuilder();
for (Item item : this) {
s.append(item);
s.append(‘ ‘);
}
return s.toString();
}

75
Q
  • 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() {</Item>
A

return new LinkedIterator(first);
}

76
Q

// a linked-list iterator
private class LinkedIterator implements Iterator<Item> {</Item>

A

private Node<Item> current;</Item>

    public LinkedIterator(Node<Item> first) {
        current = first;
    }

    public boolean hasNext() {
        return current != null;
    }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = current.item;
        current = current.next;
        return item;
    }
}
77
Q

/**
* Unit tests the {@code Queue} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Queue<String> queue = new Queue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
queue.enqueue(item);
else if (!queue.isEmpty())
StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}
}</String></String>

A

Queue<String> queue = new Queue<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-"))
queue.enqueue(item);
else if (!queue.isEmpty())
StdOut.print(queue.dequeue() + " ");
}
StdOut.println("(" + queue.size() + " left on queue)");
}
}</String></String>

78
Q

Iteration.

A

To consider the task of implementing iteration, we start with a snippet of client code that prints all of the items in a collection of strings, one per line:

Stack<String> collection = new Stack<String>();
...
for (String s : collection)
StdOut.println(s);
...</String></String>

79
Q

This foreach statement is shorthand for the following while statement:

A

Iterator<String> i = collection.iterator();
while (i.hasNext()) {
String s = i.next();
StdOut.println(s);
}</String>

80
Q

To implement iteration in a collection:

A

Include the following import statement so that our code can refer to Java’s java.util.Iterator interface:

import java.util.Iterator;

Add the following to the class declaration, a promise to provide an iterator() method, as specified in the java.lang.Iterable interface:

implements Iterable<Item></Item>

Implement a method iterator() that returns an object from a class that implements the Iterator interface:

public Iterator<Item> iterator() {
return new LinkedIterator();
}</Item>

Implement a nested class that implements the Iterator interface by including the methods hasNext(), next(), and remove(). We always use an empty method for the optional remove() method because interleaving iteration with operations that modify the data structure is best avoided.
The nested class LinkedIterator in Bag.java illustrates how to implement a class that implements the Iterator interface when the underlying data structure is a linked list.
The nested class ArrayIterator in ResizingArrayBag.java does the same when the underlying data structure is an array.

81
Q

How does autoboxing handle the following code fragment?

Integer a = null;
int b = a;

A

How does autoboxing handle the following code fragment?

Integer a = null;
int b = a;

82
Q

Why does the first group of statements print true, but the second false?

Integer a1 = 100;
Integer a2 = 100;
System.out.println(a1 == a2); // true

Integer b1 = new Integer(100);
Integer b2 = new Integer(100);
System.out.println(b1 == b2); // false

Integer c1 = 150;
Integer c2 = 150;
System.out.println(c1 == c2); // false

A

The second prints false because b1 and b2 are references to different Integer objects. The first and third code fragments rely on autoboxing. Surprisingly the first prints true because values between -128 and 127 appear to refer to the same immutable Integer objects (Java’s implementation of valueOf() retrieves a cached values if the integer is between -128 and 127), while Java constructs new objects for each integer outside this range.

83
Q

Are generics solely for auto-casting?

A

No, but we will use them only for “concrete parameterized types”, where each data type is parameterized by a single type. The primary benefit is to discover type-mismatch errors at compile time instead of run time. There are other more general (and more complicated) uses of generics, including wildcards. This generality is useful for handling subtypes and inheritance

84
Q

Can concrete parameterized types be used in the same way as normal types?

A

Yes, with a few exceptions (array creation, exception handling, with instanceof, and in a class literal).

85
Q

Can I make the Node class static?

A

For LinkedStackOfString.java, you can do so with no other changes and save 8 bytes (of inner class overhead) per node. However, the nested class Node in LinkedStack.java uses the type information of Item from the outer class, so you would need to do a bit of extra work to make it static. Stack.java accomplishes this by making the nested class (and the nester iterator) generic: there are three separate generic type parameters, each of which is named Item.

86
Q

Why do I get a “can’t create an array of generics” error when I try to create an array of generics?

public class ResizingArrayStack<Item> {
Item[] a = new Item[1];</Item>

A

Unfortunately, creating arrays of generics is not possible in Java 1.5. The underlying cause is that arrays in Java are covariant, but generics are not. In other words, String[] is a subtype of Object[], but Stack<String> is not a subtype of Stack<object>. To get around this defect, you need to perform an unchecked cast as in ResizingArrayStack.java. ResizingArrayStackWithReflection.java is an (unwieldy) alternative that avoids the unchecked cast by using reflection.</object></String>

87
Q

So, why are arrays covariant?

A

Many programmers (and programming language theorists) consider covariant arrays to be a serious defect in Java’s type system: they incur unnecessary run-time performance overhead (for example, see ArrayStoreException) and can lead to subtle bugs. Covariant arrays were introduced in Java to circumvent the problem that Java didn’t originally include generics in its design, e.g., to implement Arrays.sort(Comparable[]) and have it be callable with an input array of type String[].

88
Q

Can I create and return a new array of a parameterized type, e.g., to implement a toArray() method for a generic queue?

A

Not easily. You can do it using reflection provided that the client passes an object of the desired concrete type to toArray() This is the (awkward) approach taken by Java’s Collection Framework. GenericArrayFactory.java provides an alternate solution in which the client passes a variable of type Class. See also Neal Gafter’s blog for a solution that uses type tokens.

89
Q

Why is the construct called foreach if it uses the keyword for?

A

Other languages use the keyword foreach, but the Java developers did not want to introduce a new keyword and break backward compatibility.

90
Q

Are Strings iterable?

A

No.

91
Q

Are arrays Iterable?

A

No. You can use the foreach syntax with them. However, you can not pass an array to a method that expects an Iterable or return an array from a method which returns an Iterable. This would be convenient, but it doesn’t work that way.

92
Q

What’s wrong with the following code fragment?

String s;
for (s : listOfStrings)
System.out.println(s);

A

The enhanced for loop requires that the iterating variable be declared inside the loop.