Array Array creation

Arrays are represented by arrays, where numeric types, Boolean types, and character types all have Array representations.

arrayOf()

fun main(a) {
    var int_array: Array<Int> = arrayOf(1.2.3)
    // The data type of the variable can be omitted, i.e. :
    var boolean_array = arrayOf(true.false.true)
    var string_array = arrayOf("Hello"."World"."~")}Copy the code

This method can also create arrays containing different data types:

var arr = arrayOf(1.2.3.43.3 f.'a'."Hello")
for (v in arr) {
    print(v)
    print("\t")}Copy the code

arrayOfNulls<Int>(3)

Creates an array with a given number of elements of the specified data type that can be empty:

var arr = arrayOfNulls<Int> (3)
arr[0] = 1
arr[1] = 2
arr[3] = 3
Copy the code

The factory functionArray()

Array() => The first argument represents the number of elements in the Array, and the second argument is an expression using the subscripts of its elements. For example, in Array(3,{I -> (I *2).tostring ()}), because there are three elements in the Array that start with 0,1,2, the I in the second argument starts with 0,1,2, and then goes into the expression given by the second argument.

var arr = Array(5,{i -> (i+1).toString()})
for (i in arr) {
    print(i)
    print("\t")}Copy the code

Primitive array

Note: There is no stringArrayOf().

fun main(a) {
    var int_array = intArrayOf(1.2.3)
    var boolean_array = booleanArrayOf(true.false.true)}Copy the code

As mentioned earlier, there is no stringArrayOf() method, but in the rookie tutorial it is claimed that this class eliminates the need for boxing and is therefore more efficient, so it is worth remembering.


Array complement: Common operations

arr.withIndex():forLoop through a set of elements and their markers

fun main(a) {
	var arr = arrayOf(1.2.3)
	for ((index,it) in arr.withIndex()) {
		println("$index : $it")}}Copy the code

For maximum

fun main(a) {
	val arr = arrayOf(1.2.3)
	var max = 0
	for (i in arr) {
		if (max<i) {
			max = i
		}
	}
	println("maximum: ${max}")}Copy the code

arr[0]=10andArr. Set (0, 10): Modifies array elements

fun main(a) {
	val arr = arrayOf(1.2.3)
	arr[0] = 133
	arr.set(1.1999)
	arr.forEachIndexed() {
		index, it -> println("$index : $it")}}/ / 0:133
/ / 1:1999
/ / 2:3
Copy the code

Find element markers

  • IndexOf (num) : Finds the first corner of a specified element

  • IndexOfFirst (num) : Finds the first corner of the specified element

  • LastIndexOf (num) : Finds the last corner of the specified element

  • IndexOfLast (num) : Finds the last corner of the specified element