【问题标题】:How to Convert Set (HashSet) to Array in Kotlin?如何在 Kotlin 中将 Set (HashSet) 转换为数组?
【发布时间】:2018-07-16 19:54:46
【问题描述】:

我有一组字符串

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

我需要将其转换为数组

val array = arrayOf("a", "b", "c")

【问题讨论】:

    标签: arrays kotlin set hashset


    【解决方案1】:

    使用扩展函数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>
    }
    

    【讨论】:

    • 这就是解决方案。
    【解决方案2】:

    将集合(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]
    

    【讨论】:

      【解决方案3】:

      只需val array = set.toArray()

      【讨论】:

      • 它不能正常工作:Type mismatch. Required: Array&lt;String&gt; Found: Array&lt;(out)Any!&gt;!
      • @AbnerEscócio 我在 Intellij IDEA 中尝试过,效果很好。是Array&lt;(out)Any&gt;!,没有问题。
      【解决方案4】:

      你可以打电话

      val array = set.toArray()
      

      使用 Kotlin 1.2.51 测试。

      【讨论】:

      • 它不能正常工作:类型不匹配。必需:Array 找到:Array!
      猜你喜欢
      • 2018-12-24
      • 2015-06-20
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 2010-12-08
      • 2021-03-13
      相关资源
      最近更新 更多