/* * 集合类型-数组 * 1.有序可重复-Array索引从0开始 * 2.无序不重复-set * 3.无序可重复-Map,但值有唯一的键 * */ fun main(args: Array<String>) { //Array:Array<类型>或arrayof(元素1,元素2.元素3....元素n) //大小固定,元素类型不可变 // var stations= Array<String>("重庆","上海") var stations1= arrayOf("重庆","上海","北京","上海")//常用 for (s in stations1) { println(s)//--->>重庆 上海 北京 上海 } //获取筛选重复元素的数组:.distinct 或用.to Set转换为Set val norepeat=stations1.distinct() val norepeat1=stations1.toSet() for (s in norepeat) { print(s)//--->>重庆上海北京 } //切割数组:sliceArray val slice=stations1.slice(1..2)//下标--->>上海北京 for (slouse in slice) { print(slouse) } //创建一个有默认值的数组 Array(长度,{默认值}) var name=Array(20,{"默认值"}) for (s1 in name) { println(s1)//--->>默认值 默认值。。。。默认值 } //创建1-10数组:Array(10,i->i+1) //i代表元素的索引值从0开始 var a=Array(10,{i->i}) for (i in a){ println(i)//--->>0 1 2 3 4 5 6 7 8 9 } //元素计数:count(),空否:isEmpty() println(a.count())//数组长度-->>10 println(a.isEmpty())//--->>false //获取其中元素:数组名[索引],首元素:数组名.first,尾元素:数组名.last //获取前5个元素的快捷方法.component1到5 println(a.first())//---->0 println("${a.component1()},${a.component5()}")//--->>0,4 println(a[5])//获取第六个元素--->>5 //mutableList:MutableList<类型>或mutableListof(元素1.元素2,,,元素n) //大小可变,类型不可变 var stationsnew= mutableListOf("重庆","上海","北京","上海") var stationsnew1= arrayOf("涪陵","长寿") //在末尾增加:add()方法 // 添加另一个数组addAll方法 stationsnew.add("广州") stationsnew.addAll(stationsnew1) for (s in stationsnew) { print(s)//------>>重庆上海北京上海广州涪陵长寿 } //移除元素remove,移出指定位置removeAt stationsnew.removeAt(0) stationsnew.removeAll(stationsnew1) } 总结: Array:Array<类型>或arrayof(元素1,元素2.元素3....元素n)创建的数组 -----大小固定,元素类型不可变 没见有添加删除方法--(有待认证) mutableList:MutableList<类型>或mutableListof(元素1.元素2,,,元素n) ---大小可变,类型不可变 有添加,移除方法 stationsnew.add("广州") stationsnew.removeAt(0)
val asc = Array(5, { i -> i * 2 })---需要指定长度
参考:https://www.cnblogs.com/my334420/p/7070763.html