Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with n copies of the same value/object?

Tags:

java

arrays

copy

I want to create an array of size n with the same value at every index in the array. What's the best way to do this in Java?

For example, if n is 5 and the value is the boolean false, the array should be:

= [false, false, false, false, false] 
like image 763
XåpplI'-I0llwlg'I - Avatar asked Jan 11 '13 10:01

XåpplI'-I0llwlg'I -


2 Answers

You can try it with:

boolean[] array = new boolean[5]; Arrays.fill(array, false); 

Second method with manual array fill:

boolean[] array = new boolean[] {false, false, false, false, false}; 
like image 89
hsz Avatar answered Sep 21 '22 19:09

hsz


List<Integer> copies = Collections.nCopies(copiesCount, value); 

javadoc here.

This is better than the 'Arrays.fill' solution by several reasons:

  1. it's nice and smooth,
  2. it consumes less memory (see source code) which is significant for a huge copies amount or huge objects to copy,
  3. it creates an immutable list,
  4. it can create a list of copies of an object of a non-primitive type. That should be used with caution though because the element itself will not be duplicated and get() method will return the same value for every index. It's better to provide an immutable object for copying or make sure it's not going to be changed.

And lists are cooler than arrays :) But if you really-really-really want an array – then you can do the following:

Integer[] copies = Collections.nCopies(copiesCount, value)                               .toArray(new Integer[copiesCount]); 
like image 21
Innokenty Avatar answered Sep 24 '22 19:09

Innokenty