Quiz 02 sample questions and answers

In the first question, you will read some code and write a concise, high-level, English description of the code’s action. For example:

public static <E> List<E> mystery(List<E> l, int i) {
  List<E> r = new ArrayList<>();
  for (int j = i; j < l.size(); j++) {
    r.add(l.get(j));
  }
  return r;
}

This method returns a new list composed of the last i elements of l in the order they appear in l.

(An aside: Remember, classes can be generic, and you indicate it with a type parameter after the class name. Methods can be generic, too, and you indicate it with a type parameter immediately before the method’s return type. That’s what the <E> between static and List<E> in this method’s signature is saying: the method is parameterized on type .)


In the second question, you’ll identify a logic error in a short snippet of code. That is, you will find a conceptual error, not an error that the compiler would catch. Here is an example:

/** 
  * Swaps the `i`th and `j`th elements of the List `l`. 
  * Assume 0 <= i <= j <= l.size().   
  */
public static <E> void swap(List<E> l, int i, int j) {
  l.set(i, l.get(j));
  l.set(j, l.get(i));
}

This method overwrite the element at i with the element at j, but does not overwrite the element at j with the element at i. (A temp variable is needed.)


In the final question, you will write a short class or method according to a textual description. For example, a question might state:

Write a method static <E> List<E> concatenate(List<E> l1, List<E> l2). concatenate should return, as a new list, all the elements of l1 followed by all the elements of l2, in the order they appeared.

For example, with an input of l1 = [1, 2, 5], l2 = [2, 4, 1]', it should return the list[1, 2, 5, 2, 4, 1]`.

Assume List and ArrayList are correctly imported.

One acceptable answer:

public static <E> List<E> concatenate(List<E> l1, List<E> l2) {
  List<E> r = new ArrayList<>();
  for (E e: l1) {
    r.add(e);
  }
  for (E e: l2) {
    r.add(e);
  }
  return r;
}

Another possible answer:

public static <E> List<E> concatenate(List<E> l1, List<E> l2) {
  List<E> r = new ArrayList<>(l1);
  r.addAll(l2);
  return r;
}