Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #284 Create a zeroed list of integers

Create a new list a (or array, or slice) of size n, where all elements are integers initialized with the value 0.

import static java.util.stream.IntStream.iterate;
int a[] = iterate(0, i -> 0).limit(n).toArray();
import static java.util.stream.IntStream.range;
int a[] = range(0, n).map(i -> 0).toArray();
import java.util.stream.IntStream;
int[] a = IntStream.generate(() -> 0)
                .limit(n)
                .toArray();

IntStream from java 8.
Box after limit to create a List<Integer>.
import static java.util.stream.IntStream.range;
import java.util.ArrayList;
import java.util.List;
List<Integer> a = new ArrayList<>(n);
range(0, n).forEach(i -> a.add(0));
import static java.util.Arrays.fill;
Integer a[] = new Integer[n];
fill(a, 0);
int a[] = new int[n];

The default `int` value in Java, is 0.
int[] a = new int[n];

Java automatically initializes integer arrays with zeros.
import java.util.*;
List<Integer> a = new ArrayList<Integer>(n);
for (int i =0;i<n;i++){
    a.add(0);
}
#include <stdlib.h>
int *a = calloc(n, sizeof(*a));

calloc automatically sets every byte allocated to 0.

New implementation...