【发布时间】:2009-10-29 15:57:46
【问题描述】:
考虑以下两个sn-ps代码:
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,因此 index 肯定会大于 ArrayList 的大小。
但是,在第二种情况下,我希望对ensureCapacity 的调用会增长strings,这样对add 的调用就会在索引676 处正确插入字符串"foo" - 但事实并非如此。
为什么不呢?
我应该怎么做才能让
add(index, "foo")为index > strings.size()工作?
【问题讨论】: