在 Kotlin 中如何将 Set(HashSet)转换为数组?

8

我有一组字符串

 val set = HashSet<String>()
    set.add("a")
    set.add("b")
    set.add("c")

我需要将它转换为数组。
val array = arrayOf("a", "b", "c")
4个回答

21

使用扩展函数 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
那就是解决方案。 - Adam Arold

0

只需使用val array = set.toArray()


它不能正常工作:类型不匹配。需要:Array<String>,找到:Array<(out)Any!>! - Abner Escócio
@AbnerEscócio 我在Intellij IDEA中尝试了一下,它可以正常工作。它是Array <(out) Any>!,没有任何问题。 - user8959091

0

你可以直接调用

val array = set.toArray()

已测试通过 Kotlin 1.2.51。


它无法正常工作: 类型不匹配。需要:Array<String>,找到:Array<(out)Any!>! - Abner Escócio

0

将 Set(HashSet) 转换为数组

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)}")

}

当您运行程序时,输出将为:
Array: [a, b, c]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接