ArrayList 的初始大小 [英] Initial size for the ArrayList

查看:27
本文介绍了ArrayList 的初始大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以通过执行以下操作来设置 ArrayList 的初始大小

You can set the initial size for an ArrayList by doing

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

然而,你不能这样做

arr.add(5, 10);

因为它会导致越界异常.

because it causes an out of bounds exception.

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

What is the use of setting an initial size if you can't access the space you allocated?

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

The add function is defined as add(int index, Object element) so I am not adding to index 10.

推荐答案

您将数组列表的大小与其容量混淆了:

You're confusing the size of the array list with its capacity:

  • size 是列表中元素的数量;
  • 容量是列表在不重新分配其内部结构的情况下可以容纳的元素数量.
  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

当您调用 new ArrayList(10) 时,您正在设置列表的初始容量,而不是其大小.换句话说,以这种方式构造时,数组列表的生命周期是空的.

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.

向数组列表添加十个元素的一种方法是使用循环:

One way to add ten elements to the array list is by using a loop:

for (int i = 0; i < 10; i++) {
  arr.add(0);
}

完成此操作后,您现在可以修改索引 0..9 处的元素.

Having done this, you can now modify elements at indices 0..9.

这篇关于ArrayList 的初始大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆