Quiz 03 sample questions and answers
The quiz will have three questions, and cover material through the end of the Set
topics.
In the first 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?
Note: there was an error in this answer originally! It showed the union (A ∪ B = {1, 2, 3, 4, 6}) rather than the intersection.
{2}
In the second and third questions, you will write a short class or method according to a textual description. 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> result = new ArrayList<>();
for (E e: list) {
if (!set.contains(e)) {
result.add(e);
}
}
return result;
}
Another question might state:
Write a generic class MySet<E>
that extends an existing implementation of Set
. MySet
should include a method public List<E> asList()
. asList
returns a new list consisting of the elements of the current set.
asList
must not modify the set. 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
, Set
, ArrayList
, and HashSet
are correctly imported from java.util
. You may not import other classes.
public class MySet<E> extends HashSet<E> {
public List<E> asList() {
return new ArrayList<E>(this);
}
}