Kotlin-存储并读取在Hashmap中的数组



noob to kotlin。我有一个hashmap,它将为其中一个钥匙存放一个阵列。但是,当我阅读该键的值时,Kotlin并未将其识别为数组。

我的哈希玛普:

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

阅读数组:

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

当我尝试读取值时,我会遇到类型不匹配错误。我以不正确的方式将阵列存储在hashmap中?

我的hashmap类型是hashmap。我只是现在指定该值的类型,并且以后将动态存储实际值。

所以稍后我阅读myhashmap [" test"],我会期待类似[" Hello":" 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

实现这一目标的任何更快的方法?

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

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

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

如果您希望myHashMap["test"]返回["Hello": "World", "ABC": 3],则应该是一张地图。进入它的一种方法可以是:

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

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

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

hashMapOf("test" to arrayOf<HashMap<String, Any>>())将导致以下内容:

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

mapOf("test" to mapOf("Hello" to "World", "ABC" to 3))会导致这样的事情:

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

作为背景:"Hello" to "World"是地图的条目。您可以在mapOf中添加多个,然后将其连接到完整的5月。您的代码看起来会构建一系列地图,每个地图都只有一个条目。

wrt您的更新:如果您想在地图中拥有地图,也可以像这样写:

myhashmap [" test"] = mapof(" hello"到" world"," abc"至3(

如果您以后要添加键,也应该使用mutableMapOf。否则myHashMap["newTests"] = ...将不起作用。

在您此处提到的示例中, var testString =" __ $ {myhashmap [" test"]。count((} __"

您会遇到错误,因为myhashmap [" test"]可能为null,在这种情况下。Count((会抛出NullPoInterException。

示例 - 在这里,您创建了使用键"测试"的哈希姆普,并尝试访问相同的哈希图。尝试运行此 -

println(myhashmap ["虚拟"](//输出-Null

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

  1. !! ->这意味着即使对象为null,并且您仍然希望调用.count((。

示例 - myhashmap ["虚拟"] !!。count((结果是NullpoInterException

  1. ? ->这意味着如果myhashmap ["虚拟"]返回null。
  2. ,则不想致电count((

示例 - myhashmap ["虚拟"]?count((结果在这里是null

最新更新