This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: Why set the initial size?

You can set the initial size of ArrayList by doing the following:

ArrayList<Integer> arr=new ArrayList<Integer>(10);
Copy the code

But you can’t

arr.add(5.10);
Copy the code

Because it causes out-of-scope exceptions.

What’s the use of setting the initial size if you can’t access the allocated space?

The definition of add is add(int index, Object Element) so I’m not adding index 10.

I ran it myself and the following is an error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 0
	at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:787)
	at java.base/java.util.ArrayList.add(ArrayList.java:512)
	at Util.TestJue.main(TestJue.java:15)
Copy the code

Answer 1:

You have confused the size of the arraylist with its capacity:

Size is the number of elements in the list.

2. Capacity is how many elements a list can potentially accommodate without reallocating its internal structure.

When you call new ArrayList<Integer>(10), you are setting the initial capacity of the list, not the size of the list. In other words, when constructed this way, the arraylist’s initial value is empty.

One way to add ten elements to an arraylist is to use loops:

for (int i = 0; i < 10; i++) {
  arr.add(0);
}
Copy the code

After that, you can change the index to 0.. The element of 9.

Answer 2:

If you want to use a list of predefined sizes, you can also use:

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

Answer 3:

You can also use the Collections class

ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10.0));
Copy the code

This will add 10 zeros to your ARR