Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fill arrays in Java?

Tags:

java

arrays

I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.

like image 514
William Avatar asked Feb 23 '09 08:02

William


People also ask

How do you fill in an array?

Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.

Which method is used to fill array?

fill() method is in java. util. Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.

How do you populate values in an array?

Array.fill For example, if we want to set up an array with ten slots and populate it with the string “hello” we'd write some code like this: let filledArray = new Array(10). fill('hello'); This method works great for immutable values like numbers, strings, and booleans.


2 Answers

Check out the Arrays.fill methods.

int[] array = new int[4]; Arrays.fill(array, 1); // [1, 1, 1, 1] 
like image 69
cdmckay Avatar answered Oct 18 '22 16:10

cdmckay


You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0}; 
like image 41
Chad Birch Avatar answered Oct 18 '22 15:10

Chad Birch