Quiz 03 sample questions and answers
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> list1, List<E> list2) {
List<E> result = new ArrayList<>();
for (E e: list) {
if (!list2.contains(e)) {
result.add(e);
}
}
return result;
}
or, if you are a little more fluent in the Java API:
public static <E> List<E> notIn(List<E> list, List<E> list2) {
List<E> result = new ArrayList<>(list);
result.removeAll(list2);
return result;
}
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 class MyList<E> extends ArrayList<E> {
public List<E> reversed() {
List<E> reversed = new ArrayList<>();
for (int i = size() - 1; i >= 0; i--) {
reversed.add(get(i));
}
return reversed;
}
}