我的ArrayList分是这样的:

var amplititudes : ArrayList<Int> = ArrayList()

我想用随机整数填充这个.我该怎么做?

推荐答案

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() }

Kotlin相关问答推荐

&x是T&q;和&q;(x为?T)!=空(&Q;)?

Scala与Kotlin中的迭代

Rabin-Karp字符串匹配的实现(Rolling hash)

为什么记得不将 StateFlow 转换为特定类型?

Kotlin 列表扩展功能

在 SplashActivity 中显示的 Firebase 应用内消息.如何在 MainActivity 中显示它?

如何使用 Findbugs 避免 kotlin 文件

从列表中的每个对象中 Select 属性

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

如何在MVVM架构中观察RecyclerView适配器中的LiveData?

Firestore - 如何在 Kotlin 中排除数据类对象的字段

Kotlin not nullable值可以为null吗?

如何捕获传递给模拟函数的参数并返回它?

Kotlin - 是否可以在类中的 init 块之前初始化伴随对象?

Kotlin数据类打包

uses-sdk:minSdkVersion 16 不能小于库中声明的版本 23

如何将vararg作为数组传递给Kotlin中的函数?

Recyclerview: listen to padding click events

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module