You're confusing the size of the array list with its capacity:
- the size is the number of elements in the list;
- the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.
When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.
One way to add ten elements to the array list is by using a loop:
for (int i = 0; i < 10; i++) {
arr.add(0);
}
Having done this, you can now modify elements at indices 0..9.
Answer from NPE on Stack OverflowYou're confusing the size of the array list with its capacity:
- the size is the number of elements in the list;
- the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.
When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.
One way to add ten elements to the array list is by using a loop:
for (int i = 0; i < 10; i++) {
arr.add(0);
}
Having done this, you can now modify elements at indices 0..9.
If you want a list with a predefined size you can also use:
List<Integer> arr = Arrays.asList(new Integer[10]);
how to set a maximum size for ArrayList?
ArrayList default initialization size
[JAVA] Why is my ArrayList size always 0
[Java] How to write .size() method for an ArrayList?
Videos
I'm reading that an ArrayList has a default size of 10 once initialized. If that is the case why does the following code throw IndexOutOfBoundsException ?
public class Test {
public static void main(String[] args) {
List list = new ArrayList < > ();
list.add(0,"ONE");
list.add(1, "TWO");
list.add(5, "THREE");
System.out.println(list);
}
}