Create an ArrayList of Specific Size in Java

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

where N is the capacity with which ArrayList is created.

The size we mentioned is just the initial capacity with which the ArrayList is created. But, it does not limit you from adding elements beyond the size N, and expand the ArrayList.

Example 1 – Create an ArrayList with Specific Size

In the following program, we will create an ArrayList of strings with size 3.

Java Program

import java.util.ArrayList;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<String> names = new ArrayList<String>(3);
		names.add("Google");
		names.add("Apple");
	}
}
ADVERTISEMENT

Conclusion

In this Java Tutorial, we learned how to create an ArrayList with size N.