【问题标题】:Find index of Custom List - Kotlin查找自定义列表的索引 - Kotlin
【发布时间】:2022-10-01 10:41:01
【问题描述】:

我有一个清单

val SongList = [SongInfo(name=Dark Star, rawId=2131689475, time=1:30), SongInfo(name=Can\'t let go, rawId=2131689474, time=1:24), , SongInfo(name=Big Digits, rawId=2131689473, time=0:49), SongInfo(name=What\'s Mine, rawId=2131689478]

为了得到歌名,我这样做了

val song = songList[0].name

洗牌歌

songList.shuffle()

洗牌后如何找到歌曲索引?

  • 所以如果一首歌从索引 0 到索引 2 被洗牌,你想得到 0,而不是 2?
  • 我想要洗牌后的索引,所以它是2。有人给出了正确的答案并删除了它。
  • 洗牌列表不存在方法,但数组。代替列表有洗牌方法。

标签: kotlin


【解决方案1】:

我的代码不是最好的解决方案,但它会找到索引,并按索引返回歌曲名称。

data class SongInfo(var name: String, var rawId: String, var time: String)

fun main() {
    val songList = listOf(
        SongInfo(name = "Dark Star", rawId = "2131689475", time = "1:30"),
        SongInfo(name = "Can't let go", rawId = "2131689474", time = "1:24"),
        SongInfo(name = "Big Digits", rawId = "2131689473", time = "0:49"),
        SongInfo(name = "What's Mine", rawId = "2131689478", time = "22:31")
    )
    val song = songList[0].name
    val shuffledSongList = songList.shuffled()
    println(shuffledSongList)
    var index = 0
    while (true) {
        if (shuffledSongList[index].name == song) break
        index++
    }
    println(shuffledSongList[index].name)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多