How do I set the size of a list in Java?



Java list size is dynamic. It increases automatically whenever you add an element to it, and this exceeds the initial capacity. You can define the initial capacity at the time of list creation so that it allocates memory after the initial capacity is exhausted.

We can do this using the ArrayList Constructor and Collections.nCopies() method. In this article, we will explore both methods to set the size of a list in Java.

Let's explore these methods in detail.

Using ArrayList Constructor

We can create an ArrayList with a specific size using the ArrayList constructor. This will create an empty list with the specified initial capacity, but it will not restrict the number of elements that can be added to the list. The size of the list will grow dynamically as elements are added.

Syntax

The syntax for creating an ArrayList with a specific size is as follows:

List<Integer> list = new ArrayList<Integer>(10);

We should use index > 0 to add an element, otherwise you will get an IndexOutOfBoundsException as the index will be out of range, considering size is 0 and index > size().

The list provides the size() method to get the count of the elements present in the list. It returns the number of elements in the list.

Example

In the example below, we will create a List with a specific size and then add elements to it.

import java.util.ArrayList;
import java.util.List;
public class SetSizeOfList {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(10);
      
      list.add(1);
      list.add(2);
      list.add(3);
      
      System.out.println("Size of the list: " + list.size());
   }
}

Output

Following is the output of the above code:

Size of the list: 3

Using Collections.nCopies()

Let's create a list with a specific size using the Collections.nCopies() method. This method creates an immutable list containing the specified number of copies of the specified element.

If we use this method to initialize a list, it won't allow us to add or remove elements from the list, as it creates an immutable list.

Syntax

List<T> nCopies(int n, T o)

Example

In the below example, we will create a list of integers with a specific size using the Collections.nCopies() method.

If you try to add an element to this list, it will throw an UnsupportedOperationException because the list is immutable.

import java.util.Collections;
import java.util.List;
public class SetSizeOfList {
   public static void main(String[] args) {
      List<Integer> list = Collections.nCopies(5, 0);
      
      System.out.println("List of size 5: " + list);
      
      // list.add(1);
   }
}

Output

Following is the output of the above code:

List of size 5: [0, 0, 0, 0, 0]
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-06-10T15:08:24+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements