1.
Q1: The following method is intended to return a String formed by concatenating elements from the parameter
words
. The elements to be concatenated start with startIndex
and continue through the last element of words
and should appear in reverse order in the resulting string.
import java.util.ArrayList;
// Assume words.size() > 0 and startIndex >= 0
public String concatWords(ArrayList<String> words, int startIndex) {
String result = "";
/* missing code */
return result;
}
For example, the following code segment should print CarHouseGorilla:
ArrayList<String> things = new ArrayList<>();
things.add("Bear");
things.add("Apple");
things.add("Gorilla");
things.add("House");
things.add("Car");
System.out.println(concatWords(things, 2));
Which of the following code segments is a correct replacement for
/* missing code */
?
I.
for (int k = startIndex; k < words.size(); k++) {
result += words.get(k) + words.get(words.size() - k - 1);
}
II.
int k = words.size() - 1;
while (k >= startIndex) {
result += words.get(k);
k--;
}
III.
ArrayList<String> temp = new ArrayList<>(words);
Collections.reverse(temp);
for (int k = 0; k < temp.size() - startIndex; k++) {
result += temp.get(k);
}
- I only
- II only
- III only
- I and II only
- II and III only