【发布时间】:2011-12-12 10:55:46
【问题描述】:
根据文档,您可以在列表中的任意位置插入对象:
此界面的用户可以精确控制每个元素在列表中的插入位置。
(来源:http://download.oracle.com/javase/6/docs/api/java/util/List.html)
但以下程序失败并出现 IndexOutOfBoundsException:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<String>();
myList.add(0, "derp");
myList.add(2, "herp");
for (String s : myList) {
System.out.println("Le string: " + s);
}
}
}
它也无助于显式设置初始容量(这是有道理的,因为默认值为 10)。
为什么我不能在任何位置插入对象,只要它的索引低于容量?大小是否总是等于插入元素的数量?
【问题讨论】:
标签: java list indexoutofboundsexception