你可以通过下面的操作来设置数组列表的初始大小

ArrayList<Integer> arr=new ArrayList<Integer>(10);

然而,你不能这样做

arr.add(5, 10);

因为它会导致出界异常。

如果不能访问所分配的空间,那么设置初始大小有什么用呢?

添加函数定义为add(int index, Object element),所以我没有添加到索引10。


当前回答

如果你想要一个预定义大小的列表,你也可以使用:

List<Integer> arr = Arrays.asList(new Integer[10]);

其他回答

如果要添加带有索引的元素,则可以使用数组。

    String [] test = new String[length];
    test[0] = "add";

10是AL的初始容量,而不是size (size是0)。当你要有很多元素时,你应该把初始容量提到一个较高的值,因为它避免了在不断添加元素时扩展容量的开销。

这可能会帮助到一些人

ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(new Integer[10]));

尽管你的数组列表的容量是10,但实际的数组中没有元素。add方法用于将元素插入到实际列表中。因为它没有元素,所以不能在索引5中插入一个元素。

普通发布版. .

List <Destination\> destinations = Collections.nCopies(source.size(), Destination.class.newInstance());