如何仅通过提供大小在 Kotlin 中像在 Java 中一样创建数组?
如何像在 java 中那样创建数组?
How can I create a Array like we do in java?
int A[] = new int[N];
我怎样才能在 Kotlin 中做到这一点?
How can I do this in Kotlin?
根据 reference,数组的创建方式如下:
According to the reference, arrays are created in the following way:
对于 Java 的原始类型,有不同的类型
IntArray
、DoubleArray
等,它们存储 未装箱值.
For Java's primitive types there are distinct types
IntArray
,DoubleArray
etc. which store unboxed values.
它们是用相应的构造函数和工厂函数创建的:
They are created with the corresponding constructors and factory functions:
val arrayOfZeros = IntArray(size) //equivalent in Java: new int[size]
val numbersFromOne = IntArray(size) { it + 1 }
val myInts = intArrayOf(1, 1, 2, 3, 5, 8, 13, 21)
第一个和 Java 中的类似,它只是创建一个用默认值填充的原始数组,例如Int
为零,false
表示 Boolean
.
The first one is simillar to that in Java, it just creates a primitive array filled with the default value, e.g. zero for Int
, false
for Boolean
.
非原始数组由 Array
类表示,其中 T
是项目类型.
Non primitive-arrays are represented by Array<T>
class, where T
is the items type.
T
仍然可以是 Java 中的基本类型之一(Int
, Boolean
,...),但里面的值将是等效于 Java 的 Integer
、Double
等.
T
can still be one of types primitive in Java (Int
, Boolean
,...), but the values inside will be boxed equivalently to Java's Integer
, Double
and so on.
此外,T
可以是 可为空和非空 类似于 String
和 String?
.
Also, T
can be both nullable and non-null like String
and String?
.
它们的创建方式类似:
val nulls = arrayOfNulls<String>(size) //equivalent in Java: new String[size]
val strings = Array(size) { "n = $it" }
val myStrings = arrayOf("foo", "bar", "baz")
val boxedInts = arrayOfNulls<Int>(size) //equivalent in Java: new Integer[size]
val boxedZeros = Array(size) { 0 }