繁体   English   中英

这就是我用 Kotlin 中的值初始化列表的方式吗?

[英]Is this how I initialize a list with values in Kotlin?

我想为每个值存储多个计数,如下所示:

value count
0  -> 6
1  -> 2
2  -> 0
3  -> 7

如示例中所示,值从 0 开始并且是连续整数。

我想用 0 初始化所有计数,以便我可以增加它们。

这就是我想出的:

val histogram = Array(numBuckets) { 0 }.toMutableList() as ArrayList
histogram[2]++

它可以工作,但初始化感觉有点复杂。 有没有更好的办法? ArrayList 是该地点工作的正确集合吗?

您可以只使用MutableList构造函数:

val histogram = MutableList(numBuckets) { 0 }

如果值-计数对中的值是连续的并且从 0 开始,Kevin Coppock 的答案很有效。那么数组或列表索引代表值-计数对中的值。

如果需要更大的灵活性,例如,如果值

  • 不要从零开始,
  • 有一个不是 1 的步骤,
  • 或有不规则的步骤(例如对数),

以 Pair<Int, Int> 或数据类的形式引入对可能是有意义的:

import kotlin.math.pow

data class HistogramEntry(
  var value: Int,
  var count: Int
)

例子:

val numBuckets = 5

val regularHistogram = List(numBuckets) { HistogramEntry(it, 0) }

regularHistogram[2].count++

regularHistogram(::println)

输出:

HistogramEntry(value=0, count=0)
HistogramEntry(value=1, count=0)
HistogramEntry(value=2, count=1)
HistogramEntry(value=3, count=0)
HistogramEntry(value=4, count=0)

另一个例子:

val numBuckets = 5

val logarithmicHistogram = List(numBuckets) { HistogramEntry(10f.pow(it + 1).toInt(), 0) }

logarithmicHistogram[2].count = 12345

logarithmicHistogram.forEach(::println)

输出:

HistogramEntry(value=10, count=0)
HistogramEntry(value=100, count=0)
HistogramEntry(value=1000, count=12345)
HistogramEntry(value=10000, count=0)
HistogramEntry(value=100000, count=0)

当然,也可以手动构建 HistogramEntry 列表:

val list = listOf(
  HistogramEntry(value = 234, count = 0),
  HistogramEntry(value = 36, count = 0),
  HistogramEntry(value = 9, count = 0),
  HistogramEntry(value = 178, count = 0),
  HistogramEntry(value = 11, count = 0)
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM