List:只读列表,列表创建后不能被修改。
MutableList: 可以在创建后被修改,这意味着你可以添加、删除或更新它的元素。
fun main() {
val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6)
val numbers2 = listOf(1, 2, 3, 4, 5, 6)
println("List:$numbers")
println("Size:${numbers.size}")
println("First:${numbers.first()}")
println("First:${numbers.last()}")
println("Contains 4? ${numbers.contains(4)}")
println("Contains 7? ${numbers.contains(7)}")
}
List:[1, 2, 3, 4, 5, 6]
Size:6
First:1
First:6
Contains 4? true
Contains 7? false
在只读列表中添加或更改元素是不被允许的
val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6)
numbers.add(7) //不被允许
numbers[0] = 7 //不被允许
reversed
返回一个新列表,其中的元素按相反的顺序排列
sorted
返回一个新列表,其中的元素按升序排序
val colors = listOf("green", "orange", "blue")
println("Reversed list: ${colors.reversed()}")
//按字母顺序
println("Sorted list: ${colors.sorted()}")
println("List: $colors")
val oddNumbers = listOf(5, 3, 7,1)
println("List: $oddNumbers")
println("Sorted list: ${oddNumbers.sorted()}")
Reversed list: [blue, orange, green]
Sorted list: [blue, green, orange]
List: [green, orange, blue]
List: [5, 3, 7, 1]
Sorted list: [1, 3, 5, 7]
可变列表是创建后可以修改的列表。您可以添加、删除或更改
val entrees = mutableListOf()
这行code导致错误,listOf 也有这个问题
error info:Not enough information to infer type variable T
原因是:当创建一个可变列表或列表时,Kotlin尝试从传递的参数推断列表包含的元素类型
例如,如果您编写listOf(“noodles”),Kotlin推断您想要创建一个字符串列表
当初始化一个没有元素的空列表时,Kotlin无法推断元素的类型,所以您必须显式地声明类型。为此,可以在mutabllistof或listOf后的尖括号中添加类型。
正确代码:
2种方式都可以
val entrees = mutableListOf<String>()
val entrees:MutableList<String> = mutableListOf()
val entrees = mutableListOf<String>()
// val entrees:MutableList = mutableListOf()
println("Entrees:$entrees")
println("Add noodles:${entrees.add("noodles")}")
println("Entrees:$entrees")
val more = listOf("ravioli", "lasagna", "fettuccine")
println("Add list: ${entrees.addAll(more)}")
println("Entrees: $entrees")
println("Remove spaghetti: ${entrees.remove("ravioli")}")
println("Entrees: $entrees")
println("Remove first element: ${entrees.removeAt(0)}")
println("Entrees: $entrees")
entrees.clear()
println("Entrees: $entrees")
println("Empty? ${entrees.isEmpty()}")
//IndexOutOfBoundsException: Index: 0, Size: 0
println("Empty? ${entrees.removeAt(0)}")
Entrees:[]
Add noodles:true
Entrees:[noodles]
Add list: true
Entrees: [noodles, ravioli, lasagna, fettuccine]
Remove spaghetti: true
Entrees: [noodles, lasagna, fettuccine]
Remove first element: noodles
Entrees: [lasagna, fettuccine]
Entrees: []
Empty? true
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Sample
val names = listOf("Jessica", "Henry", "Alicia", "Jose")
var index = 0
while (index < names.size) {
print(names[index])
index++
}
println()
for (name in names) {
print(name)
}
println()
for (item in 'b'..'g') {
print(item)
}
println()
for (item in 1..5) {
print( "$item")
}
println()
for (item in 5 downTo 1) {
print(item)
}
println()
for (item in 3..6 step 3) {
print(item)
}
输出:
JessicaHenryAliciaJose
JessicaHenryAliciaJose
bcdefg
12345
54321
36
看下面几个类:
假如创建一个Vegetables class
val vegetables = Vegetables("Cabbage", "Sprouts", "Onion")
写法1:
class Vegetables(val topping1: String,
val topping2: String,
val topping3: String){}
写法2:
class Vegetables(val toppings: List<String>) {}
不过要传递List类型的参数
Vegetables(listOf("cabbage", "sprouts", "onion"))
写法3:
优雅的
class Vegetables(vararg val toppings: String) {
}
在Kotlin中,vararg修饰符允许您将数目可变的相同类型的参数传递给函数或构造函数。通过这种方式,您可以将不同的蔬菜作为单独的字符串而不是列表提供
Sample
class Vegetables(vararg val toppings:String){
override fun toString(): String {
return toppings.joinToString()
}
}
val vegetables = Vegetables("cabbage","onion");
println(vegetables.toString())
Run and Out
cabbage, onion
joinToString用[separator]分隔的所有元素创建一个字符串,
注意:要指定除逗号以外的其他分隔符,请将所需的分隔符字符串作为参数传递给joinToString()方法。示例:joinToString(" ")以空格分隔每个元素,具体看文档
open class Item(val name: String, val price: Int) {
}
class Noodles() : Item("Noodles", 10) {
override fun toString(): String {
return name
}
}
class Vegetables(vararg val toppings: String) : Item("Vegetables", 5) {
override fun toString(): String {
return if (toppings.isEmpty()) {
"$name Chef's Choice"
} else {
name + " " + toppings.joinToString()
}
}
}
class Order(val orderNumber: Int){
private val itemList = mutableListOf<Item>()
fun addItem(newItem:Item):Order{
itemList.add(newItem)
return this
}
fun addAll(newItems: List<Item>):Order{
itemList.addAll(newItems)
return this
}
fun print(){
println("Order #${orderNumber}")
var total = 0
for (item in itemList){
println("$item:$${item.price}")
total += item.price
}
println("Total:$$total")
}
}
Run
val ordersList = mutableListOf<Order>()
val order1 = Order(1)
order1.addItem(Noodles())
ordersList.add(order1)
val order2 = Order(2)
order2.addItem(Noodles())
order2.addItem(Vegetables())
ordersList.add(order2)
val order3 = Order(3)
val items = listOf(Noodles(), Vegetables("Carrots","Beans","Celery"))
order3.addAll(items)
ordersList.add(order3)
ordersList.add(Order(4)
.addItem(Noodles())
.addItem(Vegetables("Spinach")))
for (order in ordersList){
order.print()
println()
}
Out
Order #1
Noodles:$10
Total:$10
Order #2
Noodles:$10
Vegetables Chef’s Choice:$5
Total:$15
Order #3
Noodles:$10
Vegetables Carrots, Beans, Celery:$5
Total:$15
Order #4
Noodles:$10
Vegetables Spinach:$5
Total:$15