【发布时间】:2013-07-31 11:24:09
【问题描述】:
如果我们阅读添加函数here 的 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 上运行。
【问题讨论】:
-
因为除了前 2 个元素之外,您没有将任何元素添加到列表中,这些元素会在最后打印出来。
-
for (int i = 0; i
-
“我目前正在使用 jdk 7 并在 intellij idea 上运行。” IntelliJ IDEA 内置了一个很棒的调试器,能够逐步遍历代码-步。这几乎就像它是为解决这样的问题而设计的......
标签: java arraylist indexoutofboundsexception