为什么这段代码会抛出一个IndexOfOutBoundsException - 又名是什么,使用ensureCapacity()?

StackOverflow https://stackoverflow.com/questions/1644741

  •  10-07-2019
  •  | 
  •  

考虑以下两段代码:

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并不奇怪。 根据API add(int index, E element)将抛出IndexOfOutBoundsException <!>;如果索引超出范围(index < 0 || index > size()) <!>“;在添加任何元素之前,strings的大小为0,因此index肯定会大于ArrayList的大小。

但是,在第二种情况下,我希望调用ensureCapacity增长add,以便对"foo"的调用将正确地在索引676处插入字符串add(index, "foo") - 但事实并非如此。

  1. 为什么不呢?

  2. 我应该怎样做才能index > strings.size()适用于<=>

有帮助吗?

解决方案

ArrayList中底层数组的容量与更高级别的List API方法(添加,删除等)不同,只能说明支持数组的大小。如果要允许在列表边界之外添加元素,则需要在实用程序类中自己编写代码(或找到为您执行此操作的集合),填充空值,空对象或新应用程序在新内容之间所需的任何内容。索引和旧的大小。

其他提示

ArrayList.ensureCapacity()不会更改列表的实际大小(由size()返回),而是重新分配内部缓冲区,以便它不需要重新分配缓冲区以增长到此大小(当你调用list.add(object)。

/**
 * Increases the capacity of this <tt>ArrayList</tt> instance, if
 * necessary, to ensure that it can hold at least the number of elements
 * specified by the minimum capacity argument.
 */

粗略猜测,我认为您正在寻找的是

Integer index = Integer.valueOf(676);
Map<Integer,String> strings = new HashMap<Integer,String>();
strings.put(index, "foo");

你的长度是676,但你必须记住它们是零基础,所以实际上,你想要索引-1将是你的最大数字。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top