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"]。