【问题标题】:Kotlin - Storing and reading an array in hashmapKotlin - 在 hashmap 中存储和读取数组
【发布时间】:2019-05-17 22:07:29
【问题描述】:

Kotlin 的新手。我有一个哈希图,它将为其中一个键保存一个数组。但是,当我读取该键的值时,Kotlin 并未将其识别为数组。

我的哈希图:

var myHashMap = hashMapOf("test" to arrayOf<HashMap<String, Any>>())

读取数组:

var testString = "__ ${myHashMap["test"].count()} __"

当我尝试读取值时出现类型不匹配错误。我以不正确的方式将数组存储在 hashmap 中?

我的 hashmap 是 HashMap 类型。我现在只是指定值的类型,稍后将动态存储实际值。

所以稍后当我阅读 myHashMap["test"] 时,我会期待类似 ["Hello": "World", "ABC": 3]

编辑:添加我的解决方案

我试过了,它现在可以工作,但检查是否有更好的解决方案。

    var tests = task["test"] as ArrayList<HashMap<String, Any>>
    var testCount = tests.count()

另外,如果我现在想继续向 myHashMap["test"] 添加值,我会将现有值存储到 var 中,向其添加新值,然后将其传递给 myHashMap["test"]。

tests.add(someHashMap)
myHashMap["test"] = tests

有更快的方法来实现这一点吗?

【问题讨论】:

    标签: arrays kotlin hashmap


    【解决方案1】:

    通过类型不匹配,您指的是以下错误吗?

    error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Array&lt;kotlin.collections.HashMap&lt;String, Any&gt; /* = java.util.HashMap&lt;String, Any&gt; */&gt;?

    如果是这样,您应该将表达式更改为 "__${myHashMap["test"]?.count()}__""__${myHashMap["test"]!!.count()}__",因为 myHashMap["test"] 可以计算为 null。

    【讨论】:

      【解决方案2】:

      如果你想让myHashMap["test"]返回["Hello": "World", "ABC": 3],这应该是一张地图。一种输入方式可以是:

      mapOf("test" to mapOf("Hello" to "World", "ABC" to 3))

      这也可能是您的类型不匹配错误的原因。如上所述定义时,结果将是:

      var testString = "__ ${myHashMap["test"]!!.count()} __" // -&gt; 2

      hashMapOf("test" to arrayOf&lt;HashMap&lt;String, Any&gt;&gt;()) 会导致类似:

      {
        "test": [
          { "Hello": "World" },
          { "ABC": 3 }
        ]
      }
      

      虽然mapOf("test" to mapOf("Hello" to "World", "ABC" to 3)) 会导致这样的结果:

      {
        "test": {
          "Hello": "World",
          "ABC": 3
        }
      }
      

      作为背景:"Hello" to "World" 是地图的一个条目。您可以在mapOf 中添加多个,然后将它们连接成一个完整的可能。您的代码看起来就像您要构建一个地图数组,每个地图只有一个条目。

      WRT 你的更新:如果你想在地图中有一个地图,你也可以这样写:

      myHashMap["test"] = mapOf("Hello" 到 "World","ABC" 到 3)

      如果您想稍后添加密钥,您还应该改用mutableMapOf。否则myHashMap["newTests"] = ... 将不起作用。

      【讨论】:

        【解决方案3】:

        在你在这里提到的例子中, var testString = "__ ${myHashMap["test"].count()} __"

        您收到错误是因为 myHashMap["test"] 可能为 null,在这种情况下 .count() 会抛出 NullPointerException。

        示例 - 在这里,您使用键“test”创建了 hashmap,并尝试访问它。尝试运行这个 -

        println(myHashMap["dummy"]) // 输出 - null

        由于 kotlin 是 null 安全的,如果对象可以为 null,则需要以下 null 安全断言之一。

        1. !! -> 这意味着即使 object 为 null 并且您仍然希望调用 .count() ,您也不在乎。

        示例 - myHashMap["dummy"]!!.count() 这里的结果是 NullPointerException

        1. ? -> 这意味着如果 myHashMap["dummy"] 返回 null,则不想调用 count()。

        示例 - myHashMap["dummy"]?.count() 此处的结果将为空

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多