Collections

Java initialize ArrayList example

Java initialize ArrayList example shows how to initialize ArrayList in Java. Example also shows various approaches to initialize ArrayList and how to initialize ArrayList with all zeroes.

How to initialize ArrayList in Java?

This works perfectly for ArrayList declared in the methods. What if the ArrayList is a member variable declared at class level and you want to make sure that it is initialized before it is accessed. Use any of the below given approaches to initialize ArrayList.

1) Initialize ArrayList using anonymous inner class

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

Output

2) Initialize ArrayList using static block

You can use static block to initialize ArrayList. Static blocks are executed when the class is loaded in memory.

Output

3) Initialize ArrayList using Arrays class

You can initialize ArrayList in one line using asList method of Arrays class as given below.

Output

4) Initialize ArrayList using Java 8 stream

If you are using Java 8, you can use stream to initialize an ArrayList as given below.

Output

Above code returns unmodifiable list which you cannot change in any way. If you need to change it, use below code instead.

5) Initialize ArrayList using Collections class

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

How to initialize ArrayList with all zeros?

Consider below given code to create an ArrayList.

What it does is it creates a new ArrayList object of initial capacity of 10. How to initialize elements of an ArrayList with zeroes?

You can use nCopies of the Collection class.

This method returns a list containing specified object n times.

Output

Please let us know your views in the comments section.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.