Monday, January 30, 2017

Java recipe: Initialize an ArrayList with zeros

It's often useful to have a list filled with zeros of the specified length N.
Why would you want one? Well, it's handy during the work with algorithms, or just to avoid null checks.
Usually, instead of the List filled with 0s an Array is enough: new int[N]
- creates an array of N integers with zero value.
new ArrayList(N) (has the size 0) is NOT the same as new int[N] (has the length N)

- The integer passed to the constructor of list represents its initial capacity (the number of elements it can hold before it needs to resize its internal array) which has nothing to do with the initial number of elements in it.
Whatever, below are the bunch of ways to create the List filled with zeros, if you need one.
In each example we will create a list filled with 100 zeros. (Java8 implementation with StreamAPI included).

14 comments:



  1. It is really very helpful for us and I have gathered some important information from this blog.
    Angularjs Development Company in India

    ReplyDelete