Given I have an integer value of, e.g., 10
.
How can I create an array of 10 elements like [1,2,3,4,5,6,7,8,9,10]
?
To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.
You can make an array of int s, double s, or any other type, but all the values in an array must have the same type. To create an array, you have to declare a variable with an array type and then create the array itself.
int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable. Java populates our array with default values depending on the element type - 0 for integers, false for booleans, null for objects, etc.
You can just splat a range:
[*1..10] #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ruby 1.9 allows multiple splats, which is rather handy:
[*1..3, *?a..?c] #=> [1, 2, 3, "a", "b", "c"]
yet another tricky way:
> Array.new(10) {|i| i+1 } => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
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