Initialize all elements of an array with a specified value in Java

In this post, we will see how to initialize all elements of an array with a specified value in Java.


 

We know that an array is initialized with a default value on creation. The default value is 0 for integral types. If we need to initialize an array with a different value, we can use any of below methods:

 

1. Arrays.fill()

The most common approach is to use Arrays.fill() method which internally uses a for loop.

 

Download   Run Code

 

2. Collections.nCopies()

The idea here is to call Collections.nCopies() method to get a list and then convert it to an array using List.toArray() method.

 

Download   Run Code

 

3. Arrays.setAll()

Another alternative is to use setAll() method of the Arrays class. It sets all elements of the specified array with the help of a generator function that accepts an index and generates a corresponding value for that index. Now we can easily set a specific value for each element of the array by returning the same value for every index.

 

Download   Run Code

 

4. Java 8

In Java 8 and above, we can use Streams API which offers many alternatives as shown below:

 

Download   Run Code

 

Download   Run Code

 

Download   Run Code

 

Download   Run Code

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of