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);
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.
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.
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.
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.
Yes,
long[] arr = new long[12];
Arrays.fill(arr, 42L);
You can do this:
long[] values = new long[12];
Arrays.fill(values, 42l);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With