首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Kotlin -将列表转换为MutableList的最常用方法

Kotlin -将列表转换为MutableList的最常用方法
EN

Stack Overflow用户
提问于 2016-11-19 01:33:54
回答 3查看 32.8K关注 0票数 72

我有一个返回List<Contact>的方法(getContacts),我需要将结果转换为MutableList<Contact>。目前我能想到的最好的方法是这样做:

val contacts: MutableList<Contact> = ArrayList(presenter.getContacts())

有没有一种更惯用的/“更少的Java”方式来做到这一点呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-11-19 01:48:16

考虑使用toMutableList()函数:

presenter.getContacts().toMutableList()

有一些针对标准库类型的toMutableList()扩展,您可能希望将其转换为可变列表:Collection<T>Iterable<T>Sequence<T>CharSequenceArray<T>和原始数组。

票数 117
EN

Stack Overflow用户

发布于 2019-12-04 12:32:39

如果你只想要ArrayList,你可以创建自己的Kotlin扩展。

fun <T> List<T>.toArrayList(): ArrayList<T>{
    return ArrayList(this)
}

然后,您可以在您的应用程序中使用它,如下所示

myList.toArrayList()

简单易用

票数 12
EN

Stack Overflow用户

发布于 2020-06-07 03:47:44

如果要将ListMutableList转换为数组,也可以使用toTypedArray()

/**
 * Returns a *typed* array containing all of the elements of this collection.
 *
 * Allocates an array of runtime type `T` having its size equal to the size of this collection
 * and populates the array with the elements of this collection.
 * @sample samples.collections.Collections.Collections.collectionToTypedArray
 */
@Suppress("UNCHECKED_CAST")
public actual inline fun <reified T> Collection<T>.toTypedArray(): Array<T> {
    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    val thisCollection = this as java.util.Collection<T>
    return thisCollection.toArray(arrayOfNulls<T>(0)) as Array<T>
}

示例

myMutableList.toTypedArray()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40682918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档