java - Initial size for the ArrayList

ID : 10104

viewed : 21

Tags : javaarraylistindexoutofboundsexceptionjava

Top 5 Answer for java - Initial size for the ArrayList

vote vote


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.

vote vote


If you want a list with a predefined size you can also use:

List<Integer> arr = Arrays.asList(new Integer[10]); 
vote vote


if you want to use Collections.fill(list, obj); in order to fill the list with a repeated object alternatively you can use

ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0)); 

the line copies 10 times 0 in to your ArrayList

vote vote


Capacity of an ArrayList isn't the same as its size. Size is equal to the number of elements contained in the ArrayList (and any other List implementation).

The capacity is just the length of the underlying array which is used to internaly store the elements of the ArrayList, and is always greater or equal to the size of the list.

When calling set(index, element) on the list, the index relates to the actual number of the list elements (=size) (which is zero in your code, therefore the AIOOBE is thrown), not to the array length (=capacity) (which is an implementation detail specific to the ArrayList).

The set method is common to all List implementations, such as LinkedList, which isn't actually implemented by an array, but as a linked chain of entries.

Edit: You actually use the add(index, element) method, not set(index, element), but the principle is the same here.

vote vote


If you want to add the elements with index, you could instead use an array.

    String [] test = new String[length];     test[0] = "add"; 

Top 3 video Explaining java - Initial size for the ArrayList