According to the docs you can insert objects an any position in a List:
The user of this interface has precise control over where in the list each element is inserted.
(source: http://download.oracle.com/javase/6/docs/api/java/util/List.html)
But the following program fails with an IndexOutOfBoundsException:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<String>();
myList.add(0, "derp");
myList.add(2, "herp");
for (String s : myList) {
System.out.println("Le string: " + s);
}
}
}
It doesn't help setting initial capacity explicitly, either (which makes some sense since the default value is 10).
Why can't I insert objects at any position as long as its index is lower than the capacity? Is the size always equal to the number of inserted elements?
You can insert an object at any valid position. Take a close look at the Javadoc for add(int, E)
:
Throws:
IndexOutOfBoundsException - if the index is out of range(index < 0 || index > size())
In other words, inserting an element always increases the size of the list by 1. You can insert at either end, or in the middle... but you can't insert past the end.
The capacity of an ArrayList
is effectively an implementation detail - it controls when the backing array needs to be replaced by a larger one to cope with more elements. The size of a list is the important part here - a list with capacity 100 but size 5 is still only a list of 5 elements, and so inserting at position 67 into such a list would make no sense.