如何正确更改 SparseArray 上的 HashMap?
How to change HashMap on SparseArray correctly?
我改了:
private val map = HashMap<Int, AuthorizationContentView>()
在
private val map = SparseArray<AuthorizationContentView>()
但是我该如何解决这个问题呢?
val view = map.getOrPut(position) {
AuthorizationContentView(context = context)
}
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
}
}
我改了:
private val map = HashMap<Int, AuthorizationContentView>()
在
private val map = SparseArray<AuthorizationContentView>()
但是我该如何解决这个问题呢?
val view = map.getOrPut(position) {
AuthorizationContentView(context = context)
}
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
}
}