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

Use an array if it's enough

Java
int[] a = new int[100];

List with zeros by using Arrays

Arrays.fill lets you avoid writing own loop.

Java
Integer[] integers = new Integer[100];    // all elements are null
Arrays.fill(integers, 0);
List<Integer> list = Arrays.asList(integers);

* Watchout: Generics in Java do not apply primitives, so Arrays.asList(new int[100]) won't help you here.


List with zeros by using Collections

Collections.nCopies(N, 0) creates immutable list, so we pass this collection in our ArrayList constructor to be able to mutate it later.

Java
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 0));

List with zeros by using IntStream

IntStream is perfect to work with primitive int-valued elements

Java
List<Integer> list = IntStream.of(new int[100])
                    .boxed()
                    .collect(Collectors.toList());
  • new int[N] - creates an array filled with zeroes & length N
  • .boxed() - each element boxed to an Integer
  • .collect(Collectors.toList());

Conclusions

These are not all possible ways to have a list with zeros (you can always iterate and fill it manually ^_^), but i guess it gives a good input to achieve needed result.


see Also


17 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
  2. That was excellent blog.
    also, check Java classes in Pune

    ReplyDelete
  3. 69CDB45B35AxelF775C68609December 29, 2024 at 12:27 PM

    DE93DD4522
    takipçi

    ReplyDelete