示例代码
代码语言:javascript复制import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_test.*
/**
* Array 创建、增、删、改、查、插入
* @author lyl 20181228
* */
class ArrayActivity : AppCompatActivity() {
// 定义Int类型数组
var itemArr = intArrayOf(1,2,3,4,5,6,7,8)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
// 初始
helloArray.text = "初始:" itemArr.asList().toString() "nn"
// 添加
addItem(9)
helloArray.text = helloArray.text as String "添加:" itemArr.asList().toString() "nn"
// 删除
deleteItem(0)
helloArray.text = helloArray.text as String "删除:" itemArr.asList().toString() "nn"
// 修改
editItem(0,-1)
helloArray.text = helloArray.text as String "修改:" itemArr.asList().toString() "nn"
// 取值get
var item:Int = getItem(0)
helloArray.text = helloArray.text as String "取值:" item.toString() "nn"
// 插入
insertItem(0,-2)
helloArray.text = helloArray.text as String "插入:" itemArr.asList().toString() "nn"
}
/**
* 增加item
* @item:需添加数值
* */
fun addItem(item:Int){
var newArr = IntArray(itemArr.size 1)
for(i in itemArr.indices){
newArr[i] = itemArr[i]
}
newArr[itemArr.size] = item
itemArr = newArr
}
/**
* 删除item
* @index:删除位置下标
* */
fun deleteItem(index:Int){
var newArr = IntArray(itemArr.size - 1)
for(i in newArr.indices){
if(i < index){
newArr[i] = itemArr[i]
}else{
newArr[i] = itemArr[i 1]
}
}
itemArr = newArr
}
/**
* 修改item
* @index:修改位置下标
* @item:修改后数值
* */
fun editItem(index:Int,item:Int){
itemArr[index] = item
}
/**
* 获取item
* @index:获取位置下标
* */
fun getItem(index:Int):Int{
return itemArr[index]
}
/**
* 插入item
* @index:插入位置下标
* @item:插入位置数值
* */
fun insertItem(index:Int,item:Int){
var newArr = IntArray(itemArr.size 1)
for(i in itemArr.indices){
if(i < index){
newArr[i] = itemArr[i]
}else{
newArr[i 1] = itemArr[i]
}
}
newArr[index] = item
itemArr = newArr
}
}
运行效果
补充
- 长整型数组:数组类型为LongArray,分配方法为longArrayOf var itemArr :LongArray = longArrayOf(1, 2, 3)
- 浮点数组:数组类型为FloatArray,分配方法为floatArrayOf var itemArr :FloatArray = floatArrayOf(1.0f, 2.0f, 3.0f)
- 双精度数组:数组类型为DoubleArray,分配方法为doubleArrayOf var itemArr :DoubleArray = doubleArrayOf(1.0, 2.0, 3.0)
- 布尔型数组:数组类型为BooleanArray,分配方法为booleanArrayOf var itemArr :BooleanArray = booleanArrayOf(true, false, true)
- 字符数组:数组类型为CharArray,分配方法为charArrayOf var itemArr :CharArray = charArrayOf('a', 'b', 'c')
- 字符串数组:数组类型为Array<String>,分配方法为arrayOf var itemArr :Array<String> = arrayOf("Hello", "Kotlin", "Array")
- Kotlin Array更多介绍:https://www.kotlincn.net/docs/reference/basic-types.html#arrays
完毕。