Given the code fragment:
public static void main(String[] args) {
List colors = new ArrayList();
colors.add("green");
colors.add("red");
colors.add("blue");
colors.add("yellow");
colors.remove(2);
colors.add(3, "cyan");
System.out.print(colors);
}
What is the result?
A.
[green, red, yellow, cyan]
B.
[green, blue, yellow, cyan]
C.
[green, red, cyan, yellow]
D. Am IndexOutOfBoundsException is thrown at runtime
題解
程式第 15 行的 remove 方法,將 colors 物件裡的「blue」字串移除了。此時 colors 這個 ArrayList 物件所存的元素為 ["green", "red", "yellow"]。
程式第 16 行的 add 方法,將「cyan」字串插入至索引 3 的位置,也就是「yellow」字串的下一個位置。此時 colors 這個 ArrayList 物件所存的元素為 ["green", "red", "yellow", "cyan"]。
