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

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

然而,你不能这样做

arr.add(5, 10);

因为它会导致出界异常。

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

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


当前回答

现在你的列表中没有元素,所以当索引5不存在时,你不能添加到它。您混淆了列表的容量与其当前大小。

就叫:

arr.add(10)

将整数添加到数组列表中

其他回答

普通发布版. .

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

这可能会帮助到一些人

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

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

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

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

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

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