关于kotlin:为什么打印IntArray会显示地址而不是数组的值?

Why does printing IntArray show an address rather than the values of the array?

对于为什么当我尝试打印出任何原始类型的数组(例如以下内容)时,为什么返回一个地址而不是数组中的实际值,我有些困惑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fun notInPlaceRevers(array : IntArray): IntArray{
  val arrayB = IntArray(5)

  for (i in 0 until array.size)
      array[i] =  array[(array.size -1)  - i]

  return arrayB
}



fun main(args: Array<String>) {
  val initialArray = intArrayOf(2,3,4,5,6)

  print("${notInPlaceRevers(initialArray)}")
}

它打印出此-> [I @ 3834d63f

现在,我进行了测试,并在执行foreach循环时将其打印出每个索引中的值,例如

1
2
for(element in initialArray)
  print("$element")

这是否与kotlin像Java一样,在将对象传递给函数时,它传递对象引用的副本。 因此,在打印基本数组时,我会得到引用吗?

还有另一种更简单的方法来打印基本数组吗?


Does this have to do with how kotlin is like java where it passes a copy of a reference of the object, when passing an object to a function. So when printing a primitive array I get back the reference?

它与JVM平台有关,但与您描述的方式无关。

Kotlin将数组实现为Java数组。数组是一个对象,因此具有toString()方法。您将看到Object类中存在的toString默认实现的输出:

1
2
3
public String toString() {
    return getClass().getName() +"@" + Integer.toHexString(hashCode());
}

[I是特殊int[]类的名称,在@之后的内容仅仅是十六进制表示形式的hashCode()的返回值。巧合的是,它是从最初分配此对象的地址派生的。对象的地址可能会随每个GC周期而变化,但其hashCode()永远不会变化,因为那样会损坏。

Also is there another simpler way to print a primitive array?

是。 Kotlin定义了扩展功能contentToString

1
2
val array = arrayOf("apples","oranges","lime")
println(array.contentToString()) // [apples, oranges, lime]

It prints out this --> [I@3834d63f

它与Kotlin没有关系。这就是Java的工作方式。

Does this have to do with how kotlin is like java where it passes a copy of a reference of the object, when passing an object to a function. So when printing a primitive array I get back the reference?

我假设您没有运行Kotlin本机或Kotlin JS。它被编译为Java字节码并在JVM上运行。因此它遵循Java的规则。

Also is there another simpler way to print a primitive array?
See Mon Vrai Nom's answer

但是,我建议您改用List。直接使用数组几乎没有真正的好处,就像在Java中使用ArrayList一样。不仅您在List上具有固定的大小,而且还有许多扩展方法。

这是一个例子。

1
2
3
4
5
6
7
8
fun notInPlaceRevers(list : List<Int>): List<Int> {
    return list.mapIndexed { i , _ -> list.size - 1 - i }
}

fun main(args: Array<String>) {
    val initialList = listOf(2, 3, 4, 5, 6)
    print("${notInPlaceRevers(initialList)}")
}

它打印

1
[4, 3, 2, 1, 0]


1
2
3
4
5
6
7
import java.util.Arrays

fun main(args: Array<String>) {
    val array = intArrayOf(1, 2, 3, 4, 5)

    println(Arrays.toString(array))
}

浏览时发现了这个