I have an ArrayList
like this :
var amplititudes : ArrayList<Int> = ArrayList()
I want to populate this with random Ints. How can I do this?
To get size of Array in Kotlin, read the size property of this Array object. size property returns number of elements in this Array. We can also use count() function of the Array class to get the size.
One option is to use the array constructor as following:
var amplititudes = IntArray(10) { Random().nextInt() }.asList()
Another strategy is:
var amplititudes = (1..10).map { Random().nextInt() }
EDIT
As suggested in the comment instead of creating an instance of Random
each time it is better to initialize it once:
var ran = Random()
var amplititudes = (1..10).map { ran.nextInt() }
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