我有一个返回List<Contact>
的方法(getContacts
),我需要将结果转换为MutableList<Contact>
。目前我能想到的最好的方法是这样做:
val contacts: MutableList<Contact> = ArrayList(presenter.getContacts())
有没有一种更惯用的/“更少的Java”方式来做到这一点呢?
发布于 2016-11-19 01:48:16
考虑使用toMutableList()
函数:
presenter.getContacts().toMutableList()
有一些针对标准库类型的toMutableList()
扩展,您可能希望将其转换为可变列表:Collection<T>
、Iterable<T>
、Sequence<T>
、CharSequence
、Array<T>
和原始数组。
发布于 2019-12-04 12:32:39
如果你只想要ArrayList,你可以创建自己的Kotlin扩展。
fun <T> List<T>.toArrayList(): ArrayList<T>{
return ArrayList(this)
}
然后,您可以在您的应用程序中使用它,如下所示
myList.toArrayList()
简单易用
发布于 2020-06-07 03:47:44
如果要将List
或MutableList
转换为数组,也可以使用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()
https://stackoverflow.com/questions/40682918
复制相似问题