【发布时间】:2014-06-10 21:24:07
【问题描述】:
以下代码出现异常Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0。但不明白为什么。
public class App {
public static void main(String[] args) {
ArrayList<String> s = new ArrayList<>();
//Set index deliberately as 1 (not zero)
s.add(1,"Elephant");
System.out.println(s.size());
}
}
更新
我可以让它工作,但我试图理解这些概念,所以我将声明更改为下面但也没有工作。
ArrayList<String> s = new ArrayList<>(10)
【问题讨论】:
-
如果您仔细阅读堆栈跟踪,您会看到错误是在添加时,而不是在请求大小时。我已经相应地编辑了你的标题。
-
你说得对,我看到了异常
at java.util.ArrayList.add。
标签: java arraylist indexoutofboundsexception