这是一个非常基本的例子,我只使用了现有的方法。ArrayList的问题
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
// This should create an ArrayList of initial capacity 10
al.add(3,5); // Add 5 at index 3
al.add(7,2); // Add 2 at index 7
al.add(9,6); // Add 6 at index 9
System.out.println(al);
}
}
然而,它抛出以下异常:
异常线程 “main” java.lang.IndexOutOfBoundsException:指数:3,大小:0
我不知道为什么抛出异常。它对我来说看起来完全合法。
你不能在任意点添加。直到数组结尾http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add (int,%20E) – 2015-03-02 18:35:45
即使我做'trimToSize()' – Boyyett 2015-03-02 18:36:01
我猜[List#add()API](http://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-int-E - )应该提供足够的提示.. – 2015-03-02 18:36:28