如何用值初始化Kotlin中的数组?

时间:2022-09-25 12:37:01

In Java an array can be initialized such as:

在Java中,可以初始化数组,如:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin's array initialization look like?

Kotlin的数组初始化是什么样子的?

13 个解决方案

#1


124  

You can:

您可以:

val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)

See Kotlin - Basic Types for details.

参见Kotlin -基本类型了解详细信息。

#2


32  

Here's an example:

这里有一个例子:

fun main(args: Array<String>) {
    val arr = arrayOf(1, 2, 3);
    for (item in arr) {
        println(item);
    }
}

You can also use a playground to test language features.

您还可以使用一个游乐场来测试语言特性。

#3


30  

Worth to mention that when using kotlin builtines (e.g. intArrayOf(), longArrayOf(), arrayOf(), etc) you are not able to initialize the array with default values (or all values to desired value) for a given size, instead you need to do initialize via calling according class constructor.

值得一提的是,当使用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})

#4


19  

In Kotlin There are Several Ways.

在科特林,有几种方法。

var arr = IntArray(size) // construct with only size

Then simply initial value from users or from another collection or wherever you want.

然后简单地从用户或其他集合或您想要的任何地方初始值。

var arr = IntArray(size, { 0 } ) // construct with size and fill array with 0
var arr = IntArray(size, { it * 1 } ) // construct with size and fill with its index

We also can create array with built in function like-

我们也可以用内建函数来创建数组

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values

Another way

另一种方式

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.

You also can use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.

您还可以使用doubleArrayOf()或DoubleArray()或任何原始类型来代替Int。

#5


4  

Old question, but if you'd like to use a range:

老问题,但如果你想使用一个范围:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()

Yields nearly the same result as:

产量几乎与:

var numbers = Array(5, { i -> i*10 + 10 })

result: 10, 20, 30, 40, 50

结果:10、20、30、40、50

I think the first option is a little more readable. Both work.

我认为第一个选项更容易读。这两个工作。

#6


3  

you can use this methods

您可以使用这些方法

var numbers=Array<Int>(size,init)
var numbers=IntArray(size,init)
var numbers= intArrayOf(1,2,3)

example

例子

var numbers = Array<Int>(5, { i -> 0 })

init represents the default value ( initialize )

init表示默认值(初始化)

#7


3  

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"]

我认为有一件事值得一提,而且从文档中还不够直观,那就是,当您使用factory函数创建一个数组并指定它的大小时,数组的初始化值与它们的索引值相等。例如,在这样的数组中:val数组= array (5, {i -> i}),赋值的初始值为[0,1,2,3,4],而不是[0,0,0,0,0,0,0,0,0,0]。这就是为什么在文档中,val asc = Array(5, {i -> (i * i).toString()})生成的答案是["0"、"1"、"4"、"9"、"16")

#8


2  

You can create an Int Array like this:

您可以创建这样的Int数组:

val numbers = IntArray(5, { 10 * (it + 1) })

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

5是Int数组的大小。lambda函数是元素init函数。它在[0,4]范围内,加上1在[1,5]范围内

origin function is:

本功能是:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of the specified [size], where each element is 
        * calculated by calling the specified
        * [init] function. The [init] function returns an array element given 
        * its index.
        */
      public inline constructor(size: Int, init: (Int) -> Int)
  ...
 }

IntArray class defined in the Arrays.kt

在Arrays.kt中定义的IntArray类。

#9


1  

In my case I need to initialise my drawer items. I fill data by below code.

在我的情况下,我需要初始化我的抽屉项目。我用下面的代码填充数据。

    val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
    val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)


    // Use lambda function to add data in my custom model class i.e. DrawerItem
    val drawerItems = Array<DrawerItem>(iconsArr.size, init = 
                         { index -> DrawerItem(iconsArr[index], names[index])})
    Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)

Custom Model class-

自定义的模型类,

class DrawerItem(var icon: Int, var name: String) {

}

#10


1  

You can try this:

你可以试试这个:

var a = Array<Int>(5){0}

#11


1  

You can simply use the existing standard library methods as shown here:

您可以简单地使用现有的标准库方法,如下所示:

val numbers = intArrayOf(10, 20, 30, 40, 50)

It might make sense to use a special constructor though:

使用一个特殊的构造函数是有意义的:

val numbers2 = IntArray(5) { (it + 1) * 10 }

You pass a size and a lambda that describes how to init the values. Here's the documentation:

传递一个大小和一个lambda来描述如何初始化这些值。这是文档:

/**
 * Creates a new array of the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> Int)

#12


0  

intialize array in this way : val paramValueList : Array<String?> = arrayOfNulls<String>(5)

以这种方式初始化数组:val paramValueList: array = arrayOfNulls <字符串> (5) ?>

#13


0  

Declare int array at global

在全局中声明int数组

var numbers= intArrayOf()

next onCreate method initialize your array with value

下一个onCreate方法用值初始化数组

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //create your int array here
    numbers= intArrayOf(10,20,30,40,50)
}

#1


124  

You can:

您可以:

val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)

See Kotlin - Basic Types for details.

参见Kotlin -基本类型了解详细信息。

#2


32  

Here's an example:

这里有一个例子:

fun main(args: Array<String>) {
    val arr = arrayOf(1, 2, 3);
    for (item in arr) {
        println(item);
    }
}

You can also use a playground to test language features.

您还可以使用一个游乐场来测试语言特性。

#3


30  

Worth to mention that when using kotlin builtines (e.g. intArrayOf(), longArrayOf(), arrayOf(), etc) you are not able to initialize the array with default values (or all values to desired value) for a given size, instead you need to do initialize via calling according class constructor.

值得一提的是,当使用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})

#4


19  

In Kotlin There are Several Ways.

在科特林,有几种方法。

var arr = IntArray(size) // construct with only size

Then simply initial value from users or from another collection or wherever you want.

然后简单地从用户或其他集合或您想要的任何地方初始值。

var arr = IntArray(size, { 0 } ) // construct with size and fill array with 0
var arr = IntArray(size, { it * 1 } ) // construct with size and fill with its index

We also can create array with built in function like-

我们也可以用内建函数来创建数组

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values

Another way

另一种方式

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.

You also can use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.

您还可以使用doubleArrayOf()或DoubleArray()或任何原始类型来代替Int。

#5


4  

Old question, but if you'd like to use a range:

老问题,但如果你想使用一个范围:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()

Yields nearly the same result as:

产量几乎与:

var numbers = Array(5, { i -> i*10 + 10 })

result: 10, 20, 30, 40, 50

结果:10、20、30、40、50

I think the first option is a little more readable. Both work.

我认为第一个选项更容易读。这两个工作。

#6


3  

you can use this methods

您可以使用这些方法

var numbers=Array<Int>(size,init)
var numbers=IntArray(size,init)
var numbers= intArrayOf(1,2,3)

example

例子

var numbers = Array<Int>(5, { i -> 0 })

init represents the default value ( initialize )

init表示默认值(初始化)

#7


3  

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"]

我认为有一件事值得一提,而且从文档中还不够直观,那就是,当您使用factory函数创建一个数组并指定它的大小时,数组的初始化值与它们的索引值相等。例如,在这样的数组中:val数组= array (5, {i -> i}),赋值的初始值为[0,1,2,3,4],而不是[0,0,0,0,0,0,0,0,0,0]。这就是为什么在文档中,val asc = Array(5, {i -> (i * i).toString()})生成的答案是["0"、"1"、"4"、"9"、"16")

#8


2  

You can create an Int Array like this:

您可以创建这样的Int数组:

val numbers = IntArray(5, { 10 * (it + 1) })

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

5是Int数组的大小。lambda函数是元素init函数。它在[0,4]范围内,加上1在[1,5]范围内

origin function is:

本功能是:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * Creates a new array of the specified [size], where each element is 
        * calculated by calling the specified
        * [init] function. The [init] function returns an array element given 
        * its index.
        */
      public inline constructor(size: Int, init: (Int) -> Int)
  ...
 }

IntArray class defined in the Arrays.kt

在Arrays.kt中定义的IntArray类。

#9


1  

In my case I need to initialise my drawer items. I fill data by below code.

在我的情况下,我需要初始化我的抽屉项目。我用下面的代码填充数据。

    val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
    val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)


    // Use lambda function to add data in my custom model class i.e. DrawerItem
    val drawerItems = Array<DrawerItem>(iconsArr.size, init = 
                         { index -> DrawerItem(iconsArr[index], names[index])})
    Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)

Custom Model class-

自定义的模型类,

class DrawerItem(var icon: Int, var name: String) {

}

#10


1  

You can try this:

你可以试试这个:

var a = Array<Int>(5){0}

#11


1  

You can simply use the existing standard library methods as shown here:

您可以简单地使用现有的标准库方法,如下所示:

val numbers = intArrayOf(10, 20, 30, 40, 50)

It might make sense to use a special constructor though:

使用一个特殊的构造函数是有意义的:

val numbers2 = IntArray(5) { (it + 1) * 10 }

You pass a size and a lambda that describes how to init the values. Here's the documentation:

传递一个大小和一个lambda来描述如何初始化这些值。这是文档:

/**
 * Creates a new array of the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> Int)

#12


0  

intialize array in this way : val paramValueList : Array<String?> = arrayOfNulls<String>(5)

以这种方式初始化数组:val paramValueList: array = arrayOfNulls <字符串> (5) ?>

#13


0  

Declare int array at global

在全局中声明int数组

var numbers= intArrayOf()

next onCreate method initialize your array with value

下一个onCreate方法用值初始化数组

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //create your int array here
    numbers= intArrayOf(10,20,30,40,50)
}