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.
You can use anonymous inner class with instance initializer as given below.
You can use static block to initialize ArrayList. Static blocks are executed when the class is loaded in memory.
You can initialize ArrayList in one line using asList method of Arrays class as given below.
If you are using Java 8, you can use stream to initialize an ArrayList as given below.
Above code returns unmodifiable list which you cannot change in any way. If you need to change it, use below code instead.
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.
Please let us know your views in the comments section.