【问题标题】: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】:

    getOrPutMutableMap 中的一个扩展函数,您可以对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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 2011-04-08
      • 1970-01-01
      • 2019-02-20
      • 2015-09-07
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多