在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
当前回答
初始化数组:val paramValueList: array <String?> = arrayOfNulls<String>(5)
其他回答
在Kotlin中有几种方法。
var arr = IntArray(size) // construct with only size
然后从用户或其他集合或任何你想要的地方获取初始值。
var arr = IntArray(size){0} // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index
我们也可以用内置函数创建数组,比如-
var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values
另一种方式
var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.
你也可以使用doubleArrayOf()或DoubleArray()或任何基本类型来代替Int。
I think one thing that is worth mentioning and isn't intuitive enough from the documentation is that, when you use a factory function to create an array and you specify it's size, the array is initialized with values that are equal to their index values. For example, in an array such as this: val array = Array(5, { i -> i }), the initial values assigned are [0,1,2,3,4] and not say, [0,0,0,0,0]. That is why from the documentation, val asc = Array(5, { i -> (i * i).toString() }) produces an answer of ["0", "1", "4", "9", "16"]
值得一提的是,当使用kotlin内置程序(例如intArrayOf(), longArrayOf(), arrayOf()等)时,对于给定的大小,您不能使用默认值(或所有值为所需值)初始化数组,相反,您需要通过根据类构造函数调用来进行初始化。
// Array of integers of a size of N
val arr = IntArray(N)
// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }
在Kotlin中有几种初始化数组的方法:
劳动力素质():
var myarray = arrayOf(1,2,3,4,5)
劳动力素质():
var myarray = arrayOf<Int>(1,2,3,4,5)
使用Array构造函数:
val num = Array(3, {i-> i*1})
内置的工厂方法:
val num1 = intArrayOf(1, 2, 3, 4)
//For Byte Datatype
val num2 = byteArrayOf()
//For Character Datatype
val num3 = charArrayOf()
//For short Datatype
val num4 = shortArrayOf()
//For long
val num5 = longArrayOf()
你可以试试这个:
var a = Array<Int>(5){0}