数组在 Kotlin 中使用 Array 类来表示,它定义了 get 与 set 函数(按照运算符重载约定这会转变为 [])以及 size 属性。
kotlin 没有new关键字,数组创建也不能使用new
元素类型 元素引用类型 = 类型 (数据)
/**
* Returns an array of objects of the given type with the given [size], initialized with null values.
*/
public fun <reified @PureReifiable T> arrayOfNulls(size: Int): Array<T?>
/**
* Returns an array containing the specified elements.
*/
public inline fun <reified @PureReifiable T> arrayOf(vararg elements: T): Array<T>
/**
* Returns an array containing the specified [Double] numbers.
*/
public fun doubleArrayOf(vararg elements: Double): DoubleArray
/**
* Returns an array containing the specified [Float] numbers.
*/
public fun floatArrayOf(vararg elements: Float): FloatArray
/**
* Returns an array containing the specified [Long] numbers.
*/
public fun longArrayOf(vararg elements: Long): LongArray
/**
* Returns an array containing the specified [Int] numbers.
*/
public fun intArrayOf(vararg elements: Int): IntArray
/**
* Returns an array containing the specified characters.
*/
public fun charArrayOf(vararg elements: Char): CharArray
/**
* Returns an array containing the specified [Short] numbers.
*/
public fun shortArrayOf(vararg elements: Short): ShortArray
/**
* Returns an array containing the specified [Byte] numbers.
*/
public fun byteArrayOf(vararg elements: Byte): ByteArray
/**
* Returns an array containing the specified boolean values.
*/
public fun booleanArrayOf(vararg elements: Boolean): BooleanArray
Kotlin 中定义数组的方式
// 创建指定大小的数组
val array1 = Array(1) { i -> i * i }
// 创建指定类型指定大小的数组
val array2 = IntArray(10)
val arr5 = IntArray(6){it}
// 创建指定类型指定大小的空数组
val array3 = arrayOfNulls<Int>(5)
// 创建基本类型的数组 明确元素
val array4 = intArrayOf(1, 2, 3, 4, 5)
// 创建空数组
val empty = emptyArray<Int>()
遍历数组
- 方式一
var arr= arrayOf(1,2,3)
for (item in arr){
println(item)
}
- 方式二,通过索引
var arr= arrayOf(1,2,3)
for (index in arr.indices){
println(index)
println(arr[index])
}
- 方式三,函数式
var arr= arrayOf(1,2,3)
arr.forEach { item ->
println(item)
}
修改数组
for (index in arr.indices){
//和Java一样的修改方式
arr[index]=1
//kotlin 可以set
arr.set(index,1)
}
元素是否在数组内?
var arr= arrayOf(1,2,3)
if ( 1 in arr){
println("1确实在")
}
if ( 5 !in arr){
println("5确实不在")
}
网友评论