Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 837
Cemre Mengü Avatar asked Jan 17 '12 14:01

Cemre Mengü


People also ask

How do I create an initial ArrayList size?

To create an ArrayList of specific size, you can pass the size as argument to ArrayList constructor while creating the new ArrayList. Following the syntax to create an ArrayList with specific size. myList = new ArrayList<T>(N);

Does ArrayList size start at 0 or 1?

The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value.

What is the capacity of ArrayList in Java?

If its testing you can usually see the capacity using your favourite IDE debugger. I don't have the exact number, but 1.7 is usually the capacity growth size. So if you create an arraylist with 10 items, java will make it size 17.


1 Answers

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.

like image 83
NPE Avatar answered Oct 18 '22 07:10

NPE