arrays - 如何在 Kotlin 中将 Set (HashSet) 转换为数组?
问题描述
我有一组字符串
val set = HashSet<String>()
set.add("a")
set.add("b")
set.add("c")
我需要将其转换为数组
val array = arrayOf("a", "b", "c")
解决方案
使用扩展功能toTypedArray
如下
set.toTypedArray()
该函数属于 Kotlin 库
/**
* 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>
}
推荐阅读
- c# - 如何在 HTTP 触发的 Azure 函数中绑定模型集合?
- quickfixj - quickFixj 中自定义对象的破解实现
- visual-studio - 在 Windows 上安装 CUDA for TensorFlow
- python - 根据过滤器python更新列值
- laravel - Laravel Eloquent:获取对象而不是数组
- angular - 将打印作业直接提供给打印机 angular 6
- angular - 本地通知日期离子
- java - Java Spark 请求的路由 [/users/] 尚未在 Spark 中映射以接受:[*/*]
- microsoft-graph-api - 无法使用 Graph API 创建从 Google 导入的事件
- php - 如何在while循环中运行sql查询