Quiz 02 sample questions and answers

The quiz will have two questions; both will require you to write a short method or class. Here are two examples of the kinds of questions you’ll be asked:

Write a static method that takes as a parameter an array, and returns a List of elements in the same order as those in the array. The method should be generic on the element type of both the array and list.

public static <E> List<E> toList(E[] array) {
  ArrayList<E> list = new ArrayList<E>();
  for (E e : array) {
    list.add(e);
  }
  return list;
}

Write a class MyList that extends an existing implementation of List. MyList should include a public instance method called reversed, which returns a new instance of the list with the elements in reverse order (and which does not modify the current instance). You may assume List and ArrayList are properly imported.

public class MyList<E> extends ArrayList<E> {
    public List<E> reversed() {
        List<E> list = new ArrayList<E>();
        for (int i = size()-1; i >= 0; i--){
            list.add(get(i));
        }
        return list;
    }
}