<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # List 相關操作 [TOC] [`List`](collections-overview.html#list) 是 Kotlin 標準庫中最受歡迎的集合類型。對列表元素的索引訪問為 List 提供了一組強大的操作。 ## 按索引取元素 List 支持按索引取元素的所有常用操作: `elementAt()` 、 `first()` 、 `last()` 與[取單個元素](collection-elements.html)中列出的其他操作。List 的特點是能通過索引訪問特定元素,因此讀取元素的最簡單方法是按索引檢索它。這是通過 [`get()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/get.html) 函數或簡寫語法 `[index]` 來傳遞索引參數完成的。 如果 List 長度小于指定的索引,則拋出異常。另外,還有兩個函數能避免此類異常: * [`getOrElse()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/get-or-else.html) 提供用于計算默認值的函數,如果集合中不存在索引,則返回默認值。 * [`getOrNull()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/get-or-null.html) 返回 `null` 作為默認值。 ```kotlin fun main() { //sampleStart val numbers = listOf(1, 2, 3, 4) println(numbers.get(0)) println(numbers[0]) //numbers.get(5) // exception! println(numbers.getOrNull(5)) // null println(numbers.getOrElse(5, {it})) // 5 //sampleEnd } ``` ## 取列表的一部分 除了[取集合的一部分](collection-parts.html)中常用的操作, List 還提供 [`subList()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/sub-list.html) 該函數將指定元素范圍的視圖作為列表返回。因此,如果原始集合的元素發生變化,則它在先前創建的子列表中也會發生變化,反之亦然。 ```kotlin fun main() { //sampleStart val numbers = (0..13).toList() println(numbers.subList(3, 6)) //sampleEnd } ``` ## 查找元素位置 ### 線性查找 在任何列表中,都可以使用 [`indexOf()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index-of.html) 或 [`lastIndexOf()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/last-index-of.html) 函數找到元素的位置。它們返回與列表中給定參數相等的元素的第一個或最后一個位置。如果沒有這樣的元素,則兩個函數均返回 `-1`。 ```kotlin fun main() { //sampleStart val numbers = listOf(1, 2, 3, 4, 2, 5) println(numbers.indexOf(2)) println(numbers.lastIndexOf(2)) //sampleEnd } ``` 還有一對函數接受謂詞并搜索與之匹配的元素: * [`indexOfFirst()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index-of-first.html) 返回與謂詞匹配的*第一個元素的索引*,如果沒有此類元素,則返回 `-1`。 * [`indexOfLast()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index-of-last.html) 返回與謂詞匹配的*最后一個元素的索引*,如果沒有此類元素,則返回 `-1`。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf(1, 2, 3, 4) println(numbers.indexOfFirst { it > 2}) println(numbers.indexOfLast { it % 2 == 1}) //sampleEnd } ``` ### 在有序列表中二分查找 還有另一種搜索列表中元素的方法——[二分查找算法](https://zh.wikipedia.org/wiki/%E4%BA%8C%E5%88%86%E6%90%9C%E5%B0%8B%E6%BC%94%E7%AE%97%E6%B3%95)。它的工作速度明顯快于其他內置搜索功能,但*要求該列表按照一定的順序*(自然排序或函數參數中提供的另一種排序)按升序[排序過](collection-ordering.html)。否則,結果是不確定的。 要搜索已排序列表中的元素,請調用 [`binarySearch()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/binary-search.html) 函數,并將該值作為參數傳遞。如果存在這樣的元素,則函數返回其索引;否則,將返回 `(-insertionPoint - 1)`,其中 `insertionPoint` 為應插入此元素的索引,以便列表保持排序。如果有多個具有給定值的元素,搜索則可以返回其任何索引。 還可以指定要搜索的索引區間:在這種情況下,該函數僅在兩個提供的索引之間搜索。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf("one", "two", "three", "four") numbers.sort() println(numbers) println(numbers.binarySearch("two")) // 3 println(numbers.binarySearch("z")) // -5 println(numbers.binarySearch("two", 0, 2)) // -3 //sampleEnd } ``` #### Comparator 二分搜索 如果列表元素不是 `Comparable`,則應提供一個用于二分搜索的 [`Comparator`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator.html)。該列表必須根據此 `Comparator` 以升序排序。來看一個例子: ```kotlin data class Product(val name: String, val price: Double) fun main() { //sampleStart val productList = listOf( Product("WebStorm", 49.0), Product("AppCode", 99.0), Product("DotTrace", 129.0), Product("ReSharper", 149.0)) println(productList.binarySearch(Product("AppCode", 99.0), compareBy<Product> { it.price }.thenBy { it.name })) //sampleEnd } ``` 這是一個不可`排序`的 `Product` 實例列表,以及一個定義排序的 `Comparator`:如果 `p1` 的價格小于 `p2` 的價格,則產品 `p1` 在產品 `p2` 之前。因此,按照此順序對列表進行升序排序后,使用 `binarySearch()` 查找指定的 `Product`的索引。 當列表使用與自然排序不同的順序時(例如,對 `String` 元素不區分大小寫的順序),自定義 Comparator 也很方便。 ```kotlin fun main() { //sampleStart val colors = listOf("Blue", "green", "ORANGE", "Red", "yellow") println(colors.binarySearch("RED", String.CASE_INSENSITIVE_ORDER)) // 3 //sampleEnd } ``` #### 比較函數二分搜索 使用 _比較_ 函數的二分搜索無需提供明確的搜索值即可查找元素。 取而代之的是,它使用一個比較函數將元素映射到 `Int` 值,并搜索函數返回 0 的元素。 該列表必須根據提供的函數以升序排序;換句話說,比較的返回值必須從一個列表元素增長到下一個列表元素。 ```kotlin import kotlin.math.sign //sampleStart data class Product(val name: String, val price: Double) fun priceComparison(product: Product, price: Double) = sign(product.price - price).toInt() fun main() { val productList = listOf( Product("WebStorm", 49.0), Product("AppCode", 99.0), Product("DotTrace", 129.0), Product("ReSharper", 149.0)) println(productList.binarySearch { priceComparison(it, 99.0) }) } //sampleEnd ``` Comparator 與比較函數二分搜索都可以針對列表區間執行。 ## List 寫操作 除了[集合寫操作](collection-write.html)中描述的集合修改操作之外,[可變](collections-overview.html#集合類型)列表還支持特定的寫操作。這些操作使用索引來訪問元素以擴展列表修改功能。 ### 添加 要將元素添加到列表中的特定位置,請使用 [`add()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/add.html) 或 [`addAll()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/add-all.html) 并提供元素插入的位置作為附加參數。位置之后的所有元素都將向右移動。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf("one", "five", "six") numbers.add(1, "two") numbers.addAll(2, listOf("three", "four")) println(numbers) //sampleEnd } ``` ### 更新 列表還提供了在指定位置替換元素的函數——[`set()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/set.html) 及其操作符形式 `[]`。`set()` 不會更改其他元素的索引。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf("one", "five", "three") numbers[1] = "two" println(numbers) //sampleEnd } ``` [`fill()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fill.html) 簡單地將所有集合元素的值替換為指定值。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf(1, 2, 3, 4) numbers.fill(3) println(numbers) //sampleEnd } ``` ### 刪除 要從列表中刪除指定位置的元素,請使用 [`removeAt()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/remove-at.html) 函數,并將位置作為參數。在元素被刪除之后出現的所有元素索引將減 1。 ```kotlin fun main() { //sampleStart val numbers = mutableListOf(1, 2, 3, 4, 3) numbers.removeAt(1) println(numbers) //sampleEnd } ``` ### 排序 在[集合排序](collection-ordering.html)中,描述了按特定順序檢索集合元素的操作。對于可變列表,標準庫中提供了類似的擴展函數,這些擴展函數可以執行相同的排序操作。將此類操作應用于列表實例時,它將更改指定實例中元素的順序。 就地排序函數的名稱與應用于只讀列表的函數的名稱相似,但沒有 `ed/d` 后綴: * `sort*` 在所有排序函數的名稱中代替 `sorted*`:[`sort()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sort.html)、[`sortDescending()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sort-descending.html)、[`sortBy()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sort-by.html) 等等。 * [`shuffle()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/shuffle.html) 代替 `shuffled()`。 * [`reverse()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/reverse.html) 代替 `reversed()`。 [`asReversed()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/as-reversed.html) 在可變列表上調用會返回另一個可變列表,該列表是原始列表的反向視圖。在該視圖中的更改將反映在原始列表中。以下示例展示了可變列表的排序函數: ```kotlin fun main() { //sampleStart val numbers = mutableListOf("one", "two", "three", "four") numbers.sort() println("Sort into ascending: $numbers") numbers.sortDescending() println("Sort into descending: $numbers") numbers.sortBy { it.length } println("Sort into ascending by length: $numbers") numbers.sortByDescending { it.last() } println("Sort into descending by the last letter: $numbers") numbers.sortWith(compareBy<String> { it.length }.thenBy { it }) println("Sort by Comparator: $numbers") numbers.shuffle() println("Shuffle: $numbers") numbers.reverse() println("Reverse: $numbers") //sampleEnd } ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看