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 List<Integer> mystery(List<Integer> l, int i) {
List<Integer> 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 but i
elements of l
in the order they appear in l
.
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 void swap(List<Integer> l, int i, int j) {
l.set(i, l.get(j));
l.set(j, l.get(i));
}
This method overwrites 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 List<Integer> concatenate(List<Integer> l1, List<Integer> 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. Your code must not modify l1
or l2
.
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 List<Integer> concatenate(List<Integer> l1, List<Integer> l2) {
List<Integer> r = new ArrayList<>();
for (Integer e: l1) {
r.add(e);
}
for (Integer e: l2) {
r.add(e);
}
return r;
}
Another possible answer, that uses the copy constructor of ArrayList
and the addAll
method:
public static List<Integer> concatenate(List<Integer> l1, List<Integer> l2) {
List<Integer> r = new ArrayList<>(l1);
r.addAll(l2);
return r;
}