Quiz 04 sample questions and answers
The quiz will have three questions, and cover material through the end of the Set
topics we’ve gotten to so far.
In one question, you will show your understanding of simple set theory and notation. For example:
Suppose A = {1, 2, 3} and B = {2, 4, 6}. What is A ∩ B?
{2}
In one question, you will write a comparator. For example, a question might state:
Suppose you want to sort a list of integers into descending order. Write a class DescendingIntegerComparator
that implements Comparator
. It should allow you to use List.sort
to perform this task. For example, if the unsorted list is [2, 1, 4, 3]
, then the list should be [4, 3, 2, 1]
after sorting using this comparator.
public class DescendingIntegerComparator implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return -Integer.compare(o1, o2);
}
}
In the other questions, you will write a short class or method according to a textual description. (Yes, these are similar to last time, though the quiz questions will differ.) For example, a question might state:
Write a method public static <E> List<E> notIn(List<E> list, Set<E> set)
. notIn
should return a list that contains the elements present in list
but not present in set
.
The original list and set must not be modified. For full credit, your method must correctly use generics, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume List
, Set
, ArrayList
, and HashSet
are correctly imported from java.util
. You may not import other classes.
public static <E> List<E> notIn(List<E> list, Set<E> set) {
List<E> l = new ArrayList<>();
for (E e: list) {
if (!set.contains(e)) {
l.add(e);
}
}
return l;
}
or, more succinctly:
public static <E> List<E> notIn(List<E> list, Set<E> set) {
List<E> l = new ArrayList<>(list);
l.removeAll(set);
return l;
}
Another question might state:
Write a generic class MyList<E>
that extends an existing implementation of List
. MyList
should include a method public List<E> reversed()
. reversed
returns a new list consisting of the elements of the current list in reverse order.
reversed
must not modify the list. For full credit, your method must correctly use generic types, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume List
and ArrayList
are correctly imported from java.util
. You may not import other classes.
public List<E> reversed() {
List<E> l = new ArrayList<>();
for (int i = this.size() - 1; i >= 0; i--) {
l.add(get(i));
}
return l;
}