在Kotlin中将字符串数组设置为HashMap时出现奇怪的行为。

huangapple go评论45阅读模式
英文:

Weird behavior when set Array of Strings to HashMap in Kotlin

问题

我试图将字符串数组添加到HashMap中,但在控制台中只看到字符串的内存地址,而不是普通的字符串数组。

val map = mapOf<String, Array<String>>()
val list = listOf("sport")
val array = list.toTypedArray()
map["key"] = array

在执行这个操作之后,数组看起来类似于这样:[Ljava.lang.String;@518ed9b4

但期望看到这种行为:

map["key"] -> array("sport")

这段代码可能有什么问题呢?

英文:

I'm tryna add to HashMap Array of Strings but instead of normal Array of String I see only address in memory of String in console.

val map = mapOf&lt;String, Array&lt;String&gt;&gt;()
val list = listOf(&quot;sport&quot;)
val array = list.toTypedArray()
map[&quot;key&quot;] to array

And Array after this operation converts in smth like this — [Ljava.lang.String;@518ed9b4

But expected to see this kind of behavior:

map["key"] -> array("sport")

What's the problem might be with this sample of code?

答案1

得分: 3

Java/Kotlin中的数组没有良好的自动转换为字符串的功能(从技术上来说,它们的toString()实现)。你看到的是数组,但它并没有显示内容,而是只显示它是一个字符串数组并显示内存地址。

要显示数组的内容,你可以使用内置的contentToString()扩展函数或将其包装成列表:

println(arrayOf("sport").contentToString())
println(arrayOf("sport").asList())

顺便说一下,我认为你的示例中有一个错误。map["key"] to array 不会执行任何操作,可能应该是 map["key"] = array。此外,你示例中的map是只读的,无法向其添加项。然而,由于你已经打印了一个数组,我假设你的实际代码有些不同。

英文:

Arrays in Java/Kotlin don't have a good automatic conversion to strings (technically, their implementation of toString()). What you see is your array, but instead of showing the contents, it only says it is an array of strings and shows the memory address.

To show the contents of an array you can use builtin contentToString() extension or wrap it into a list:

println(arrayOf(&quot;sport&quot;).contentToString())
println(arrayOf(&quot;sport&quot;).asList())

BTW, I believe there is a mistake in your example. map[&quot;key&quot;] to array doesn't do anything, it should be probably map[&quot;key&quot;] = array. Also, map in your example is read-only, you can't add items to it. However, as you already got to the point you print an array, I assume your real code is a little different.

huangapple
  • 本文由 发表于 2023年2月10日 14:32:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定