如果我们在这里阅读 add 函数的 ArrayList 文档,显然在无效索引处添加元素会引发 IndexOutOfBoundsException。但是为什么下面的代码没有抛出任何异常呢?
public static void main(String args[]){
List cities = new ArrayList();
cities.add("Atlanta");
cities.add("Boston");
try {
for (int i = 10000000; i < cities.size(); i++){
try {
cities.add(i, "+");
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println(cities.size());
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println(cities);
}
输出:
[Atlanta, Boston]
Process finished with exit code 0
我目前正在使用 jdk 7 并在 intellij idea 上运行。