Kotlin 简明教程

Kotlin - Arrays

数组用于在单个变量中存储多个相同数据类型的项目,例如单个变量名称下的整数或字符串。

Arrays are used to store multiple items of the same data-type in a single variable, such as an integer or string under a single variable name.

例如,如果我们需要存储1000名员工的姓名,那么我们无需创建1000个不同的字符串变量,而只需定义一个容量为1000的字符串数组。

For example, if we need to store names of 1000 employees, then instead of creating 1000 different string variables, we can simply define an array of string whose capacity will be 1000.

与任何其他现代编程语言一样,Kotlin也支持数组,并提供了广泛的数组属性和支持函数来操作数组。

Like any other modern programming languages, Kotlin also supports arrays and provide a wide range of array properties and support functions to manipulate arrays.

Creating Arrays in Kotlin

要在Kotlin中创建一个数组,我们使用 arrayOf() 函数,并在其中以逗号分隔列表放置值:

To create an array in Kotlin, we use the arrayOf() function, and place the values in a comma-separated list inside it:

val fruits = arrayOf("Apple", "Mango", "Banana", "Orange")

我们还可以选择提供数据类型,如下所示:

Optionally we can provide a data type as follows:

val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

或者,可以使用 arrayOfNulls() 函数创建填充有null元素且大小固定的数组。

Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements.

Primitive type Arrays

Kotlin还有一些内置的工厂方法来创建基本数据类型的数组。例如,创建整数数组的工厂方法是:

Kotlin also has some built-in factory methods to create arrays of primitive data types. For example, the factory method to create an integer array is:

val num = intArrayOf(1, 2, 3, 4)

其他用于创建数组的工厂方法:

Other factory methods available for creating arrays:

  1. byteArrayOf()

  2. charArrayOf()

  3. shortArrayOf()

  4. longArrayOf()

Get and Set the Elements of an Array

我们可以通过方括号内使用索引号来访问数组元素。Kotlin数组索引从零(0)开始。因此,如果要访问数组的第四个元素,则需要提供3作为索引。

We can access an array element by using the index number inside square brackets. Kotlin array index starts with zero (0). So if you want to access 4th element of the array then you will need to give 3 as the index.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

   println( fruits [0])
   println( fruits [3])

}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Apple
Orange

Kotlin还提供了 get()set() 成员函数,用于获取和设置特定索引处的value值。查看以下示例:

Kotlin also provides get() and set() member functions to get and set the value at a particular index. Check the following example:

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

   println( fruits.get(0))
   println( fruits.get(3))

   // Set the value at 3rd index
   fruits.set(3, "Guava")
   println( fruits.get(3))
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Apple
Orange
Guava

Kotlin Array Length

Kotlin提供了名为 size 的数组属性,该属性返回数组的大小,即长度。

Kotlin provides array property called size which returns the size i.e. length of the array.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

   println( "Size of fruits array " + fruits.size )

}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Size of fruits array 4

我们还可以使用 count() 成员函数获取数组的大小。

We can also use count() member function to get the size of the array.

Loop Through an Array

我们可以使用 for 循环遍历数组。

We can use for loop to loop through an array.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

   for( item in fruits ){
      println( item )
   }

}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Apple
Mango
Banana
Orange

Check if an Element Exists

我们可以将 in 运算符与 if…​else 结合使用,以检查数组中是否存在元素。

We can use the in operator alongwith if…​else to check if an element exists in an array.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange")

   if ("Mango" in fruits){
      println( "Mango exists in fruits" )
   }else{
      println( "Mango does not exist in fruits" )
   }

}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Mango exists in fruits

Distinct Values from Array

Kotlin允许在数组中存储重复值,但同时可以使用 distinct() 成员函数获取数组中存储的不同值。

Kotlin allows to store duplicate values in an array, but same time you can get a set of distinct values stored in the array using distinct() member function.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange", "Apple")

   val distinct = fruits.distinct()
   for( item in distinct ){
      println( item )
   }
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Apple
Mango
Banana
Orange

Dropping Elements from Array

我们可以使用 drop()dropLast() 成员函数分别从头或从后丢弃元素。

We can use drop() or dropLast() member functions to drop elements from the beginning or from the last respectively.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>("Apple", "Mango", "Banana", "Orange", "Apple")

   val result = fruits.drop(2) // drops first two elements.
   for( item in result ){
      println( item )
   }
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Banana
Orange
Apple

Checking an Empty Array

我们可以使用 isEmpty() 成员函数检查数组是否为空。如果数组为空,则此函数返回true。

We can use isEmpty() member function to check if an array is empty or not. This function returns true if the array is empty.

Example

fun main(args: Array<String>) {
   val fruits = arrayOf<String>()
   println( "Array is empty : " + fruits.isEmpty())

}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

"Array is empty : true