Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way to declare a Java array with the same value for each element?

Tags:

java

arrays

This isn't terribly important, but I was curious if there was a way to write a Java one liner possibly using guava or something to populate an array with elements that all have the same value. So for example something like Arrays.getSameElementArray(new long[12], 42L);

like image 567
Jason Thompson Avatar asked Jun 27 '12 15:06

Jason Thompson


People also ask

How do you initialize an array with the same value in Java?

To initialize an Array with default values in Java, the new keyword is used with the data type of the Array The size of the Array is then placed in the rectangular brackets. int[] myArr = new int[10]; The code line above initializes an Array of Size 10.

How do you add the same element to an array in Java?

By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.

What is the correct way to declare an array in Java?

There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

What is the correct way to declare an array of integers in Java?

The syntax for declaring an array is: datatype[] arrayName; datatype : The type of Objects that will be stored in the array eg. int , char etc.


2 Answers

Yes,

long[] arr = new long[12];
Arrays.fill(arr, 42L);
like image 162
nullpotent Avatar answered Oct 10 '22 01:10

nullpotent


You can do this:

long[] values = new long[12];
Arrays.fill(values, 42l);
like image 26
Aleks G Avatar answered Oct 10 '22 00:10

Aleks G