簡體   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