溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在Kotlin開發(fā)中如何使用集合詳解

發(fā)布時間:2020-10-20 15:13:09 來源:腳本之家 閱讀:121 作者:一顆香菜 欄目:移動開發(fā)

關(guān)于 Kotlin 開發(fā)

使用 Kotlin 開發(fā) Android App 在 Java 工程師群體中變得越來越流行。如果你由于某些原因錯過了 Kotlin,我們強(qiáng)烈建議你看一下這篇文章。

對于那些處在技術(shù)前沿和喜歡 Kotlin 的開發(fā)者來說,本篇文章和他們息息相關(guān)。所以,下面就讓我們來看一下怎樣在 Kotlin 中使用集合吧。

Kotlin中的集合是基于 Java 集合的框架。本篇文章主要講的是 kotlin.collections 包中的幾個特性。

數(shù)據(jù)處理

Kotlin 中有一個拓展函數(shù)的特性,這個特性可以使 Kotlin 標(biāo)準(zhǔn)庫(stdlib)支持 JDK 的中的類的方法。舉個例子:如果你打開Kotlin 標(biāo)準(zhǔn)庫中的 open_Collection.kt 文件,你可以找到很類似于下面這樣的方法:

/**
* Returns a list containing only elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
 return filterTo(ArrayList<T>(), predicate)
}

所以,你寫的代碼可能是下面這個樣子:

val originalList = listOf(1, 2, 3, 4, 5, 6)
assertEquals(listOf(2, 4, 6), originalList.filter { it % 2 == 0 })
val originalList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val result = originalList.firstOrNull { it > 4 }
assertEquals(result, 5)
val originalList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val result = originalList.getOrElse(12) { 12 }
assertEquals(result, 12)
val originalList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val result = originalList.dropWhile { it < 5 }
assertEquals(result, listOf(5, 6, 7, 8, 9, 10))
val originalList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val result = originalList
    .dropWhile { it < 5 }
    .find { it < 7 }
assertEquals(result, 5)

你需要注意的是:filter和dropWhile 就像其他操作符一樣,返回的是一個新的事例。這意味著 originalList 不會改變。

為了更好的理解代碼底層到底發(fā)生了什么,我們打開源碼看一下 listOf() 方法:

/** Returns a new read-only list of given elements. The returned list is serializable (JVM). */
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()

由于RxJava和 Java 8 的 Stream API 包含類似的方法,所以上面的代碼和 RxJava 以及 Stream API很像。 但是由于 Android 工程師不能使用 Stream API,所以他們更多的使用的 RxJava 處理數(shù)據(jù)的方法來解決這個問題。然后,這種操作并不完全正確,原因在于:RxJava 是一個事件處理庫,而不是數(shù)據(jù)處理。所以你現(xiàn)在可以使用 Kotlin 來解決這個問題而不必?fù)?dān)心這些問題。

不可變集合

如果你對不可變對象(immutable object)感覺到很陌生的話,我們建議你先看完這個文檔 看完后,在看一下這個。

Kotlin區(qū)分可變對象(mutable object)和不可變對象(lists, sets, maps等等)的方法和其他編程語言不一樣。在使用Kotlin集合時準(zhǔn)確區(qū)分這幾種兩種對象對于避免不必要的錯誤和 bug 都非常有用。

Kotlin允許像 Java 類似的寫法創(chuàng)建 Kotlin 的集合實(shí)例。

val list = ArrayList<String>()

這是最簡單和整潔的方法. 下面這種方法是最棒的寫法:

val list: kotlin.collections.List<String> = java.util.ArrayList()

我創(chuàng)建了一個kotlin.collections.List引用,同時我們也創(chuàng)建了一個不可變的集合。如果你不是很相信的話,那么我們可以看一下源碼:

public interface List<out E> : Collection<E> {
 // Query Operations
 override val size: Int
 override fun isEmpty(): Boolean
 override fun contains(element: @UnsafeVariance E): Boolean
 override fun iterator(): Iterator<E>

 // Bulk Operations
 override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean

 // Positional Access Operations
 /**
 * Returns the element at the specified index in the list.
 */
 public operator fun get(index: Int): E

 // Search Operations
 /**
 * Returns the index of the first occurrence of the specified element in the list, or -1 if the specified
 * element is not contained in the list.
 */
 public fun indexOf(element: @UnsafeVariance E): Int

 /**
 * Returns the index of the last occurrence of the specified element in the list, or -1 if the specified
 * element is not contained in the list.
 */
 public fun lastIndexOf(element: @UnsafeVariance E): Int

 // List Iterators
 /**
 * Returns a list iterator over the elements in this list (in proper sequence).
 */
 public fun listIterator(): ListIterator<E>

 /**
 * Returns a list iterator over the elements in this list (in proper sequence), starting at the specified [index].
 */
 public fun listIterator(index: Int): ListIterator<E>

 // View
 /**
 * Returns a view of the portion of this list between the specified [fromIndex] (inclusive) and [toIndex] (exclusive).
 * The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
 */
 public fun subList(fromIndex: Int, toIndex: Int): List<E>
}

你看到源碼中沒 add() 方法,也沒有 remove() 方法,同時也沒有其他的一些方法去改變這個集合。在這個例子中,實(shí)例本身是java.util.ArrayList。 下面我們來通過一個例子來解釋為什么:

val list: kotlin.collections.MutableList<String> = java.util.ArrayList()
list.add("string")

你最好在本地的源碼中看這例子:

public interface MutableList<E> : List<E>, MutableCollection<E> {
 // Modification Operations
 override fun add(element: E): Boolean
 override fun remove(element: E): Boolean

 // Bulk Modification Operations
 override fun addAll(elements: Collection<E>): Boolean

 /**
 * Inserts all of the elements in the specified collection [elements] into this list at the specified [index].
 *
 * @return `true` if the list was changed as the result of the operation.
 */
 public fun addAll(index: Int, elements: Collection<E>): Boolean
 override fun removeAll(elements: Collection<E>): Boolean
 override fun retainAll(elements: Collection<E>): Boolean
 override fun clear(): Unit

 // Positional Access Operations
 /**
 * Replaces the element at the specified position in this list with the specified element.
 *
 * @return the element previously at the specified position.
 */
 public operator fun set(index: Int, element: E): E

 /**
 * Inserts an element into the list at the specified [index].
 */
 public fun add(index: Int, element: E): Unit

 /**
 * Removes an element at the specified [index] from the list.
 *
 * @return the element that has been removed.
 */
 public fun removeAt(index: Int): E

 // List Iterators
 override fun listIterator(): MutableListIterator<E>
 override fun listIterator(index: Int): MutableListIterator<E>

 // View
 override fun subList(fromIndex: Int, toIndex: Int): MutableList<E>
}

怎樣理解:Java 的 ArrayList 是否和 Kotlin 的 List一樣?

val list: kotlin.collections.List<String> = java.util.ArrayList()

實(shí)際上,這里并沒有什么奇怪的地方. Kotlin 的集合繼承了 Java 的 List 的接口。我們可以從 kotlin.collections.Collection.kt 文件中看到:

@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
import kotlin.comparisons.compareValues

正如之前所提的,這個文件包含了所有的集合擴(kuò)展方法。我們可以看到,我們在 Kotlin 中幾乎可以使用 Java CollectionsKT 類中的所有方法.當(dāng)然,也需要導(dǎo)入 java.util.* 。

讓我們來看一下我們在 Java 代碼中怎么調(diào)用 Kotlin 集合:

java.util.List<Integer> list = kotlin.collections.CollectionsKt.listOf(3, 4, 5);
java.util.List<Integer> filteredList = CollectionsKt.filter(list, item -> item > 4);

你現(xiàn)在可以很清楚的看到 Kotlin 集合是如何使用 Java 的 List 。所有擴(kuò)展函數(shù)都可以作為靜態(tài)方法訪問。

總結(jié)

Android 開發(fā)語言 Kotlin 是一門非常有趣的語言。它能幫助我們編寫更加簡潔和安全的代碼。初次之外,Kotlin 與 Java 兼容。

好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI