Quiz 05 sample questions

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.

  • 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.

  • 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.

  • 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()) {
    l.remove(0);
    clear(l);
  }
}
int foo(int x) {
  if (x <= 1) {
    return 0;
  }
  else if (x % 2 == 1) {
    return x + foo(x - 1);
  }
  else { // x % 2 == 0
    return x + foo(x * 2)
  }
}

You can check your answers here.