A guide on adjusting the size of an arraylist

Solution 2:
The initial size that you pass in is not the same as declaring the size for the array. You can still exceed the runtime in case of an array, but not in the dynamically growing size. The initial size of the array wrapped under the dynamically growing size is 1000.
Solution 3:
Solution 1:
You are confusing the size of the array list with its capacity. The size refers to the number of elements in the list, while the capacity indicates the maximum number of elements the list can hold without reallocating its internal structures.


Solution 1:

The confusion lies in equating the size of the array list with its capacity.

  • The size represents the count of elements within the list.
  • The list’s capacity refers to the number of elements it can potentially hold without needing to reallocate its internal structures.

By invoking

new ArrayList<Integer>(10)

, you are specifying the initial capacity of the list, not its size. Essentially, when the array list is created in this way, it begins without any elements.

An approach to include ten elements in the array list is through the utilization of a loop.

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

After completing this task, you are able to make changes to elements within the range of indices 0 to 9.


Solution 2:


Additionally, if you require a list with a predetermined size, you can utilize:

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


Solution 3:


Instead of using Collections.fill(list, obj); to fill the list with a repeated object, you have the option to use an alternative method.

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

The ArrayList is populated by copying 0 ten times into the line.

Frequently Asked Questions