问题描述
我不确定Kotlin中IntArray
和Array<Int>
之间的区别是什么,为什么不能互换使用它们:
I'm not sure what the difference between an IntArray
and an Array<Int>
is in Kotlin and why I can't used them interchangeably:
我知道在定位JVM
时IntArray
会转换为int[]
,但是Array<Int>
会转换为什么?
I know that IntArray
translates to int[]
when targeting the JVM
, but what does Array<Int>
translate to?
此外,您还可以拥有String[]
或YourObject[]
.为什么Kotlin拥有{primitive}Array
类型的类,而几乎所有的东西都可以排列成数组,而不仅是图元.
Also, you can also have String[]
or YourObject[]
. Why Kotlin has classes of the type {primitive}Array
when pretty much anything can be arranged into an array, not only primitives.
推荐答案
Array<Int>
是引擎盖下的Integer[]
,而IntArray
是int[]
.就是这样.
Array<Int>
is an Integer[]
under the hood, while IntArray
is an int[]
. That's it.
这意味着,当将Int
放入Array<Int>
时,将始终装箱(特别是使用Integer.valueOf()
调用).在IntArray
的情况下,不会进行装箱,因为它会转换为Java基本数组.
This means that when you put an Int
in an Array<Int>
, it will always be boxed (specifically, with an Integer.valueOf()
call). In the case of IntArray
, no boxing will occur, because it translates to a Java primitive array.
除了上面提到的可能的性能含义外,还可以考虑其他一些便利.原始数组可以保留未初始化的状态,并且在所有索引处都具有默认的0
值.这就是为什么IntArray
和其他原始数组的构造函数仅采用size参数的原因:
Other than the possible performance implications of the above, there's also convenience to consider. Primitive arrays can be left uninitialized and they will have default 0
values at all indexes. This is why IntArray
and the rest of the primitive arrays have constructors that only take a size parameter:
val arr = IntArray(10)
println(arr.joinToString()) // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
相反,Array<T>
没有只采用size参数的构造函数:创建后,在所有索引上都需要有效的非null T
实例以使其处于有效状态.对于Number
类型,这可能是默认的0
,但是无法创建任意类型T
的默认实例.
In contrast, Array<T>
doesn't have a constructor that only takes a size parameter: it needs valid, non-null T
instances at all indexes to be in a valid state after creation. For Number
types, this could be a default 0
, but there's no way to create default instances of an arbitrary type T
.
因此,在创建Array<Int>
时,您也可以使用带有初始化函数的构造函数:
So when creating an Array<Int>
, you can either use the constructor that takes an initializer function as well:
val arr = Array<Int>(10) { index -> 0 } // full, verbose syntax
val arr = Array(10) { 0 } // concise version
或者创建一个Array<Int?>
以避免必须初始化每个值,但是随后您每次从数组中读取数据时都会被迫处理可能的null
值.
Or create an Array<Int?>
to avoid having to initialize every value, but then you'll be later forced to deal with possible null
values every time you read from the array.
val arr = arrayOfNulls<Int>(10)
这篇关于IntArray与Array< Int>在科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!