List 語法
listOf(1,2,3)
fun main (){
val list = mutableListOf(1,2,3)
// 表示 特定位置的元素
val element = list[1]
println(element)
// result:
//2
}
加入 新元素
fun main (){
val list = mutableListOf(1,2,3)
list .add (4)
println(list)
// result:
//[1, 2, 3, 4]
}
A MutableList 加入 B MutableList 中 所包含的元素
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
var mutableList2: MutableList<Int> = mutableListOf(1,2 )
mutableList.addAll(mutableList2)
println(mutableList )
// result
// [1, 2, 3, 1, 2]
}
移除特定元素
fun main (){
val list = mutableListOf(1,2,3)
list .remove (2)
println(list)
// result:
//[ 1, 3]
}
A MutableList 移除掉 B MutableList 中 所包含的元素
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
var mutableList2: MutableList<Int> = mutableListOf(1,2 )
mutableList.removeAll(mutableList2)
println(mutableList )
// result
// [3]
}
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
var mutableList2: MutableList<Int> = mutableListOf(1,2,3)
mutableList.removeAll(mutableList2)
println(mutableList )
// result
// []
}
移除特定位置的元素
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
mutableList.removeAt(0)
println(mutableList )
}
// result:
//[2, 3]
清空所有的元素
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
mutableList.clear()
println(mutableList )
}
// result:
//[]
更改特定位置元素
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
mutableList.set(2,100)
println(mutableList )
}
// result
// [1, 2, 100]
相當於下面
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
mutableList[2] = 100
println(mutableList )
}
// result
// [1, 2, 100]
mutablList 是否 包含特定 元素 有包含為 true 不包含則為 false
有包含為 true
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
val isExistOrNot = mutableList.contains(2)
println(isExistOrNot )
}
不包含則為 false
fun main(){
var mutableList: MutableList<Int> = mutableListOf(1,2,3)
val isExistOrNot = mutableList.contains(4)
println(isExistOrNot )
}
A mutableList 是否 包含 B mutableList 中所有的元素 有為 true 否則為 false
fun main(){
var mutableList = mutableListOf<Int> (1,2,3)
var mutableList2 = mutableListOf<Int> ( 2,3)
val isExistOrNot = mutableList.containsAll(mutableList2)
println(isExistOrNot )
}
// result
//true
fun main(){
var mutableList = mutableListOf<Int> (1,2,3)
var mutableList2 = mutableListOf<Int> ( 0)
val isExistOrNot = mutableList.containsAll(mutableList2)
println(isExistOrNot )
}
// result
//false
判斷集合是否為 空 則為 true 否則為 false
fun main(){
var mutableList = mutableListOf<Int> (1,2,3)
println(mutableList.isEmpty() )
}
// result
// false
fun main(){
var mutableList = mutableListOf<Int> ()
println(mutableList.isEmpty() )
}
// result
// true