Quiz 05 sample questions and answers

Here are examples of some of the kinds of questions you may be asked:

  • Write a generic class MySet<E> that extends an existing implementation of Set. MySet should include a public instance method Set<E> difference(Set<E> other). difference returns a new set consisting of the set theoretic difference between the current set’s contents and the other set’s contents, in that order. The set theoretic difference between two sets A and B, written as A - B, consists of all the elements of A that are not in B.

    difference must not modify either set. For full credit, your method must include generic types, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may use Set and HashSet but no other classes from the java.util namespace.

public class MySet<E> extends HashSet<E> {
    public Set<E> difference(Set<E> other) {
        HashSet<E> set = new HashSet<>(this);
        set.removeAll(other); // note you could do this removal with a loop if you forgot about removeAll()
        return set;
    }
}
  • Suppose you have an empty queue of integers, and on that queue you execute the following operations:

    • add 1
    • add 2
    • remove
    • add 1
    • add 3
    • add 4
    • remove
    • add 1

    Show the contents of the queue. Clearly indicate the front and rear of the queue.

front -> [1, 3, 4, 1] <- rear
  • Suppose we have an linked-list-based implementation of a Queue<E>, built of Node<E> elements that link to one another. Further suppose it has head and tail instance variables, pointing to the first and last elements of the list, as well as an int size. Write the void add(E e) method.

    (We did this several ways in lecture; one correct version follows.)

public void add(E e) {
  size++;
  Node<E> node = new Node<>(e, null);
  if (tail == null) {
    head = node;
    tail = node;
  } else {
    tail.setNext(node);
    tail = tail.getNext();
  }
}
  • Identify the base case and the recursive case in the following recursive methods. Will they always terminate?
void clear(List<E> l) {
  if (!l.isEmpty()) { // <- the recursive case is this branch of the if statement
    l.remove(0);
    clear(l);  //
  } // else empty!  <- the base case is when we don't take the if branch
  // yes, this method will always terminate.
}
int foo(int x) {
  if (x <= 1) { // base case
    return 0;
  }
  else if (x % 2 == 1) { // recursive case
    return x + foo(x - 1);
  }
  else { // x % 2 == 0  // also a recursive case
    return x + foo(x * 2)
  }
  // this method is not guaranteed to terminate, as it will *not* make progress for most positive values of x
}