時間:2019年8月4日14:17:06
問題描述:
看下邊的小例子:
data class Man(val name: String, val age: Int, val type: Int)
fun main(args: Array<String>) {
val list = mutableListOf<Man>()
list.add(Man("wzc", 31,2))
list.add(Man("wzj", 32,1))
list.add(Man("wcx", 3,1))
list.add(Man("wcg", 7,1))
println("before sort")
for (man in list) {
println(man)
}
list.sortedWith(Comparator {lh, rh ->
if (lh.type.compareTo(rh.type) == 0) {
lh.age.compareTo(rh.age)
} else {
lh.type.compareTo(rh.type)
}
})
println("after sort")
}
/*
列印結果:
before sort
Man(name=wzc, age=31, type=2)
Man(name=wzj, age=32, type=1)
Man(name=wcx, age=3, type=1)
Man(name=wcg, age=7, type=1)
after sort
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
可以看到排序前後,打出的内容沒有絲毫變化。
解決方法:
看一下 sortedWith 的代碼:
/**
* Returns a list of all elements sorted according to the specified [comparator].
*
* The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Any?>() as Array<T>).apply { sortWith(comparator) }.asList()
return toMutableList().apply { sortWith(comparator) }
可以排序後的結果是在傳回值裡面。
修改代碼: