Skip to content

Java initialize ArrayList example

Java initialize ArrayList example shows how to initialize ArrayList in Java using various approaches. It also shows how to initialize ArrayList with all zeroes.

How to initialize ArrayList in Java?

Normally we create and add elements to the ArrayList as given below.

This works perfectly for the ArrayList declared inside the methods. But what if the ArrayList is a member variable declared at the class level and we want to make sure that it is initialized before it is accessed.

In such cases, you can use any of the below given approaches to initialize the ArrayList with default elements.

1) Using an anonymous inner class

You can use an anonymous inner class with instance initializer as given below.

Output

2) Using a static block

You can use a static block to initialize the ArrayList with default elements. The static blocks are executed when the class is first loaded into the memory.

Output

3) Using the Arrays class

You can also use the asList method of the Arrays class as given below.

Output

4) Using Java 8 stream

If you are using Java 8, you can use a stream as given below.

Output

The above code returns an unmodifiable list that you cannot change in any way. If you need to change it, use the below code instead.

5) Using Collections class

You can use addAll method of Collections class to add many values at once to the ArrayList as given below.

How to initialize an ArrayList with all zeros?

Consider below given code to create an ArrayList.

The above code creates a new ArrayList object with an initial capacity of 10. Now you can use nCopies method of the Collections class to fill the ArrayList elements with zeros.

This method returns a list containing the specified object n times.

Output

This example is a part of the ArrayList in Java Tutorial.

Please let me know your views in the comments section.

About the author

Leave a Reply

Your email address will not be published.