Step into Kotlin - 08 - 数组
来源:互联网 发布:面试谈谈工作经历知乎 编辑:程序博客网 时间:2024/05/20 16:33
目录
- 数组
- 概述
- 创建数组
- 空数组
- 访问数组元素
- 修改元素
- 遍历数组
- 遍历数组下标
- 检查下标
- 数组
摘要
创建数组(3种方法),空数组,访问元素,遍历数组,检查下标
数组
概述
- Array 类代表着数组
[]
可以用于访问数组的元素,实际上[]
被进行了操作符的重载,调用的是 Array 类的 setter 和 getter 方法
创建数组
直接指定长度
val fixedSizeArray = arrayOfNulls<Int>(5)
使用装箱操作
val arr = arrayOf(1, 2, 3)val intArr = intArrayOf(1, 2, 3) //同理还有 booleanArrayOf() 等
使用闭包进行初始化
val asc = Array(5, { i -> i * i }) //0,1,4,9,16
空数组
val empty = emptyArray<Int>()
长度为 0
的空数组
访问数组元素
val arr = arrayOf(1, 2, 3)println(asc[1]) // 1println(asc.get(1)) // 1// println(asc[10]) ArrayIndexOutOfBoundsException
[]
虽然调用的是 setter 和 getter 方法,但是编译成字节码时会被进行优化,变成直接访问数组的内存地址,所以不会造成性能损失。
修改元素
asc[1] = 10
遍历数组
for (i in asc) { println(i)}
此操作不会创建 iterator 对象,不会影响性能
遍历数组下标
for (j in asc.indices) { println(j)}
此操作不会创建 iterator 对象,不会影响性能
检查下标
if (i in asc.indices) { // i>=0 && i<asc.size() println("indices:" + i)}
0 0
- Step into Kotlin - 08 - 数组
- Step into Kotlin
- Step into Scala - 08 - 数组
- Step into Kotlin - 01 - 入门
- Step into Kotlin - 02 - 数据类型
- Step into Kotlin - 04 - 函数
- Step into Kotlin - 06 - 异常
- Step into Kotlin - 09 - 集合
- Step into Kotlin - 11 - 类
- Step into Kotlin - 13 - 包
- Step into Kotlin - 14 - 继承
- Step into Kotlin - 15 - 注解
- Step into Kotlin - 17 - 泛型
- Step into Kotlin - 22 - Xml
- Step into Kotlin - 24 - delegate
- Step into Kotlin - 05 - 流程控制
- Step into Kotlin - 12 - Object 与枚举
- Step into Kotlin - 18 - Extension 与 this
- Javascript事件模拟
- iOS 键盘收起~
- 每天游戏设计原理笔记(三)
- 在Genymotion上使用Fiddler & Wireshark抓包
- Largest Rectangle in Histogram
- Step into Kotlin - 08 - 数组
- UIWebView透明背景
- CC2540/CC2541进入PM3深度休眠的条件及其休眠机制的剖析
- Gson用法2(用Map读取文件内容)
- Intermediate Unity 3D for iOS: Part 3/3
- 提交数据到服务器
- initWithNibName 和 loadNibNamed 的区别
- js数组去重的最快方法
- Jfreechart DialPlot(二)时钟表