Initial size for the ArrayList

JavaArraylistIndexoutofboundsexception

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

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

Solution 3 - Java

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

Solution 4 - Java

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.

Solution 5 - Java

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

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

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

This might help someone -

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

Solution 9 - Java

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)

Solution 10 - Java

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

Solution 11 - Java

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);

Solution 12 - Java

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.

Solution 13 - Java

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'

Solution 14 - Java

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. */

Solution 15 - Java

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.

Solution 16 - Java

contrib..

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

Solution 17 - Java

This is a common error about forgetting that index in arrays starts at 0. You created an ArrayList with a capacity of 10. The first element is at place 0: arr.get(0) The second is at place 1: arr.get(1) ... The 10th element is at 9: arr.get(9)

You are trying to add a value to place 10 where the 11th element would go (if space would be allocated).

So.. answering your question "What is the use of setting an initial size if you can't access the space you allocated?" with this example it's clear that you did not allocate the space of your need if you want to put element on position 10 which is technically the place of the 11th element. Once again: indexing is starting with zero and ends with 9 in an array with capacity of 10!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCemre Meng&#252;View Question on Stackoverflow
Solution 1 - JavaNPEView Answer on Stackoverflow
Solution 2 - JavaGert Jan SchoneveldView Answer on Stackoverflow
Solution 3 - JavaFarzan SktView Answer on Stackoverflow
Solution 4 - JavaNatixView Answer on Stackoverflow
Solution 5 - Javauser3692587View Answer on Stackoverflow
Solution 6 - JavaBhesh GurungView Answer on Stackoverflow
Solution 7 - JavaquaylarView Answer on Stackoverflow
Solution 8 - JavaHrishikesh KadamView Answer on Stackoverflow
Solution 9 - JavaH.T. KooView Answer on Stackoverflow
Solution 10 - JavaHunter McMillenView Answer on Stackoverflow
Solution 11 - JavaunkView Answer on Stackoverflow
Solution 12 - Javaroll1987View Answer on Stackoverflow
Solution 13 - JavapantherView Answer on Stackoverflow
Solution 14 - JavasambhuView Answer on Stackoverflow
Solution 15 - Javaanch2150View Answer on Stackoverflow
Solution 16 - Javapattern cutterView Answer on Stackoverflow
Solution 17 - JavaBlondCodeView Answer on Stackoverflow