对于以下代码,我得到异常 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)
最佳答案
ArrayList索引从0(零)开始
您的数组列表大小为 0,并且您要在第一个索引处添加 String 元素。如果不在第 0 个索引处添加元素,则无法添加下一个索引位置。这是错误的。
所以,简单地把它变成
s.add("Elephant");
或者你可以
s.add(0,"Elephant");
关于java - 在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288439/