考虑以下两段代码:
int index = 676;
List<String> strings = new ArrayList<String>();
strings.add(index, "foo");
和
int index = 676;
List<String> strings = new ArrayList<String>();
strings.ensureCapacity(index);
strings.add(index, "foo");
在第一种情况下,我对看到 IndexOfOutBoundsException 并不感到惊讶。 According to the API , add(int index, E element)
将抛出 IndexOfOutBoundsException “如果索引超出范围 (index < 0 || index > size())
”。 strings
的大小在添加任何元素之前为 0,因此索引肯定会大于 ArrayList 的大小。
但是,在第二种情况下,我希望调用 ensureCapacity
成长strings
这样调用 add
将正确插入字符串 "foo"
在索引 676 - 但它没有。
为什么不呢?
我应该怎么做才能
add(index, "foo")
适用于index > strings.size()
?
最佳答案
ArrayList 中底层数组的容量不同于更高级别的 List API 方法(添加、删除等),并且仅与支持数组的大小有关。如果你想允许添加列表边界之外的元素,你需要在实用程序类中自己编写代码(或找到一个为你做这件事的集合),填充空值、空对象,或者你的应用程序在新的之间期望的任何东西索引和旧大小。
关于java - 为什么此代码会抛出 IndexOfOutBoundsException - 即 ensureCapacity() 是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1644741/