Consider the following two snippets of code:
int index = 676;
List<String> strings = new ArrayList<String>();
strings.add(index, "foo");
and
int index = 676;
List<String> strings = new ArrayList<String>();
strings.ensureCapacity(index);
strings.add(index, "foo");
In the first case, I'm not surprised to see an IndexOfOutBoundsException. According to the API, add(int index, E element)
will throw an IndexOfOutBoundsException "if the index is out of range (index < 0 || index > size())
". The size of strings
is 0 before any elements have been added, so index will definitely be larger than the ArrayList's size.
However, in the second case, I would expect the call to ensureCapacity
to grow strings
such that the call to add
would correctly insert the string "foo"
at index 676 - but it doesn't.
Why not?
What should I do so that
add(index, "foo")
works forindex > strings.size()
?