Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

IntArray vs Array<Int> in Kotlin

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:

missmatch

I know that IntArray translates to int[] when targeting the JVM, but what does Array<Int> translate to?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Array<Int> is an Integer[] under the hood, while IntArray is an int[]. That's it.

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.


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

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.

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...