[java] Initial size for the ArrayList

You can set the initial size for an ArrayList by doing

ArrayList<Integer> arr=new ArrayList<Integer>(10);

However, you can't do

arr.add(5, 10);

because it causes an out of bounds exception.

What is the use of setting an initial size if you can't access the space you allocated?

The add function is defined as add(int index, Object element) so I am not adding to index 10.

This question is related to java arraylist indexoutofboundsexception

The answer is


10 is the initial capacity of the AL, not the size (which is 0). You should mention the initial capacity to some high value when you are going to have a lots of elements, because it avoids the overhead of expanding the capacity as you keep adding elements.


Being late to this, but after Java 8, I personally find this following approach with the Stream API more concise and can be an alternative to the accepted answer.

For example,

Arrays.stream(new int[size]).boxed().collect(Collectors.toList())

where size is the desired List size and without the disadvantage mentioned here, all elements in the List are initialized as 0.

(I did a quick search and did not see stream in any answers posted - feel free to let me know if this answer is redundant and I can remove it)


I guess an exact answer to your question would be:

Setting an intial size on an ArrayList reduces the nr. of times internal memory re-allocation has to occur. The list is backed by an array. If you specify i.e. initial capacity 0, already at the first insertion of an element the internal array would have to be resized. If you have an approximate idea of how many elements your list would hold, setting the initial capacity would reduce the nr. of memory re-allocations happening while you use the list.


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

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

Right now there are no elements in your list so you cannot add to index 5 of the list when it does not exist. You are confusing the capacity of the list with its current size.

Just call:

arr.add(10)

to add the Integer to your ArrayList


I faced with the similar issue, and just knowing the arrayList is a resizable-array implementation of the List interface, I also expect you can add element to any point, but at least have the option to define the initial size. Anyway, you can create an array first and convert that to a list like:

  int index = 5;
  int size = 10;

  Integer[] array = new Integer[size];
  array[index] = value;
  ...
  List<Integer> list = Arrays.asList(array);

or

  List<Integer> list = Arrays.asList(new Integer[size]);
  list.set(index, value);

This might help someone -

ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(new Integer[10]));

ArrayList myList = new ArrayList(10);

//  myList.add(3, "DDD");
//  myList.add(9, "III");
    myList.add(0, "AAA");
    myList.add(1, "BBB");

    for(String item:myList){
        System.out.println("inside list : "+item);
    }

/*Declare the initial capasity of arraylist is nothing but saving shifting time in internally; when we add the element internally it check the capasity to increase the capasity, you could add the element at 0 index initially then 1 and so on. */


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.


Although your arraylist has a capacity of 10, the real list has no elements here. The add method is used to insert a element to the real list. Since it has no elements, you can't insert an element to the index of 5.


contrib..

List <Destination\> destinations = Collections.nCopies(source.size(), Destination.class.newInstance());

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


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

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

If you want to add 10 items to your ArrayList you may try that:

for (int i = 0; i < 10; i++)
    arr.add(i);

If you have already declare an array size variable you would use the variable size instead of number '10'


My two cents on Stream. I think it's better to use

IntStream.generate(i -> MyClass.contruct())
         .limit(INT_SIZE)
         .collect(Collectors.toList());

with the flexibility to put any initial values.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to indexoutofboundsexception

Java string split with "." (dot) Initial size for the ArrayList ArrayIndexOutOfBoundsException when using the ArrayList's iterator Why doesn't list have safe "get" method like dictionary? How do I get the first n characters of a string without checking the size or going out of bounds? IndexError: list index out of range and python Java substring: 'string index out of range'