【问题标题】:How to change HashMap on SparseArray correctly?如何正确更改 SparseArray 上的 HashMap?
【发布时间】:2020-05-03 13:21:23
【问题描述】:
我变了:
private val map = HashMap<Int, AuthorizationContentView>()
开
private val map = SparseArray<AuthorizationContentView>()
但是我该如何解决这里的情况呢?
val view = map.getOrPut(position) {
AuthorizationContentView(context = context)
}
【问题讨论】:
标签:
android
kotlin
hashmap
sparse-matrix
【解决方案1】:
getOrPut 是MutableMap 中的一个扩展函数,您可以对SparseArray 执行相同的操作,也可以使用您自己的自定义扩展函数。这就是 Kotlin 的方便之处:)
/**
* Returns the value for the given key. If the key is not found in the SparseArray,
* calls the [defaultValue] function, puts its result into the array under the given key
* and returns it.
*/
public inline fun <V> SparseArray<V>.getOrPut(key: Int, defaultValue: () -> V): V {
val value = get(key)
return if (value == null) {
val answer = defaultValue()
put(key, answer)
answer
} else {
value
}
}