在 Kotlin 中建立一個空的可變列表
-
在 Kotlin 中使用
mutableListOf()方法 -
在 Kotlin 中使用
arrayListOf()方法 - 在 Kotlin 中使用資料結構的建構函式
- 在 Kotlin 中使用隱式宣告
- まとめ
在深入研究示例之前,我們必須瞭解處理型別 List 資料時的兩個常用術語。
這些術語包括可變的和不可變的。可變列表是可以通過在資料結構中新增或刪除元素來修改的列表。
不可變列表是不能通過在資料結構中新增或刪除元素來修改的列表。
從這兩個術語,我們可以有兩種型別的列表,包括 List 和 MutableList。請注意,MutableList 是一個列表,因為它繼承自 List 介面。
MutableList 型別返回一個可以修改的列表,List 型別返回一個不能修改的列表。但是,當你建立 List 的實現而不指定列表是可變的還是不可變的時,預設情況下假定它是可變的。
本教程將教我們如何建立一個空的可變列表。空列表意味著資料結構中沒有元素。
在 Kotlin 中使用 mutableListOf() 方法
轉到 IntelliJ 並建立一個新的 Kotlin 專案。在 kotlin 資料夾下建立一個名為 Main.kt 的新 Kotlin 檔案。
複製以下程式碼並將其貼上到檔案中。
val mutableEmptyList: MutableList<String> = mutableListOf();
fun main() {
println(mutableEmptyList.isEmpty());
mutableEmptyList.add("I am the first element !")
println(mutableEmptyList.isEmpty());
}
mutableListOf() 方法返回一個 MutableList 型別的空列表,這意味著我們可以在資料結構中新增和刪除元素。要驗證這一點,你可以在返回的物件上呼叫 add() 或 remove() 方法。
執行上面的程式碼,注意 isEmpty() 方法在新增任何元素之前返回 true,在新增元素後返回 false,如下所示。
true
false
在 Kotlin 中使用 arrayListOf() 方法
註釋前面的示例並將以下程式碼貼上到 Main.kt 檔案中。
val mutableEmptyList: MutableList<String> = arrayListOf();
fun main() {
println(mutableEmptyList.isEmpty());
mutableEmptyList.add("I am the first element !")
println(mutableEmptyList.isEmpty());
}
arrayListOf() 方法返回一個空的 ArrayList,但在前面的示例中,我們返回一個 MutableList。這怎麼可能?
在介紹部分,我們提到 MutableList 是一個 List,因為它繼承自 List 介面;由於 ArrayList 實現了 List 介面,我們可以使用 ArrayList 返回 MutableList。
一旦我們可以訪問可變列表,我們就可以呼叫 isEmpty() 方法來驗證該方法是否為空。執行上面的程式碼,觀察輸出如下圖。
true
false
在 Kotlin 中使用資料結構的建構函式
註釋前面的示例並將以下程式碼貼上到 Main.kt 檔案中。
import java.util.LinkedList
val mutableEmptyList: MutableList<String> = LinkedList();
fun main() {
println(mutableEmptyList.isEmpty());
mutableEmptyList.add("I am the first element !")
println(mutableEmptyList.isEmpty());
}
LinkedList 類實現了 List 介面,它幫助我們返回一個 LinkedList 型別的 MutableList。
LinkedList() 建構函式返回一個空列表並應用於實現 List 介面的其他資料結構的建構函式。
執行上面的示例並注意輸出列印與其他示例相同。輸出如下所示。
true
false
在 Kotlin 中使用隱式宣告
註釋前面的示例並將以下程式碼貼上到 Main.kt 檔案中。
val mutableEmptyList = ArrayList<String>();
fun main() {
println(mutableEmptyList.isEmpty());
mutableEmptyList.add("I am the first element !")
println(mutableEmptyList.isEmpty());
}
正如你在前面的示例中所指出的,我們直接指定了我們想要的返回型別,即 MutableList。在介紹部分中,我們提到如果我們不指定是否需要只讀列表,則假定任何列表實現都是可變的。
這個例子展示瞭如何通過定義一個 List 實現隱式返回 MutableList 而不指示返回型別。
執行上面的程式碼,注意從 AbstractCollection 類繼承的 isEmpty() 方法在新增任何元素之前返回 true,在新增元素後返回 false。輸出如下所示。
true
false
まとめ
在本教程中,我們學習瞭如何使用不同的方法建立一個空的 MutableList,包括:使用 mutableListOf() 方法,使用 arrayListOf() 方法,使用資料結構的建構函式,以及使用隱式宣告方法。
David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.
LinkedIn GitHub