我有一套弦乐
val set = HashSet<String>()
set.add("a")
set.add("b")
set.add("c")
我需要将其转换为数组
val array = arrayOf("a", "b", "c")
答案 0 :(得分:7)
按如下所述使用扩展功能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>
}
答案 1 :(得分:0)
将集合(HashSet)转换为数组
URLSessionDataTask
运行程序时,输出为:
import java.util.*
fun main(args: Array<String>) {
val set = HashSet<String>()
set.add("a")
set.add("b")
set.add("c")
val array = arrayOfNulls<String>(set.size)
set.toArray(array)
println("Array: ${Arrays.toString(array)}")
}
答案 2 :(得分:0)
仅val array = set.toArray()
答案 3 :(得分:0)
您可以致电
val array = set.toArray()
使用Kotlin 1.2.51测试。