About binarySearch() of Kotlin List



我在本地的Android Studio中运行了官方Kotlin文档中的示例,发现结果与我预期的不同,但我不知道是什么导致了这种情况?

data class Produce(
val name: String,
val price: Double
)

这是我定义的数据类


val list2 = listOf(
Produce("AppCode", 52.0),
Produce("IDEA", 182.0),
Produce("VSCode", 2.75),
Produce("Eclipse", 1.75)
)

这是我的来源清单


println(list2.sortedWith(compareBy<Produce> {
it.price
}.thenBy {
it.name
}))

控制台上的输出为:

[Produce(name=Eclipse, price=1.75), Produce(name=VSCode, price=2.75), Produce(name=AppCode, price=52.0), Produce(name=IDEA, price=182.0)]

我像这个一样呼叫binarySearch()

println("result: ${
list2.binarySearch(
Produce("AppCode", 52.0), compareBy<Produce> {
it.price
}.thenBy {
it.name
}
)
}")

我认为结果应该是2,但是0

result: 0

我不知道为什么会变成这样。请帮帮我。非常感谢

sortedWith()不修改列表,它返回一个新的、排序的集合。当调用list2.binarySearch()时,您仍然可以搜索原始的、未排序的列表。

你需要做一些类似的事情:

list2.sortedWith().binarySearch()

或者使用mutableListOf()创建列表,然后使用原地排序的sort()

布罗特是对的。您需要将排序的列表传递给binarySearch()函数。在代码中澄清:
val comparator = compareBy<Produce> { it.price }.thenBy { it.name }
val sorted = list2.sortedWith(comparator)
println(sorted.joinToString("n"))
val foundIndex = sorted.binarySearch(Produce("AppCode", 52.0), comparator)
println("Found at: $foundIndex")

结果:

Produce(name=Eclipse, price=1.75)
Produce(name=VSCode, price=2.75)
Produce(name=AppCode, price=52.0)
Produce(name=IDEA, price=182.0)
Found at: 2

最新更新