簡體   English   中英

Scala中toSet的返回類型是什么

[英]What is the return type of toSet in Scala

假設我有一個Int的 Scala 數組arr 考慮arr.toSet 我知道toSet返回一個Set object。 這是Set a HashSet還是默認的TreeSet

toSet返回的值的編譯時類型Set

def toSet[B >: A]: immutable.Set[B]

但是toSet返回的toSet可能會有所不同,我們可以使用 Scala REPL 檢查

Array(1).toSet.getClass                 // class immutable.Set$Set1
Array(1, 2).toSet.getClass              // class immutable.Set$Set2
Array(1, 2, 3).toSet.getClass           // class immutable.Set$Set3
Array(1, 2, 3, 4).toSet.getClass        // class immutable.Set$Set4
Array(1, 2, 3, 4, 5).toSet.getClass     // class immutable.HashSet
Array(1, 2, 3, 4, 5, 6).toSet.getClass  // class immutable.HashSet
...

哪個輸出

假設我有一個Int的 Scala 數組arr 考慮arr.toSet 我知道toSet返回一個Set object。 這是Set a HashSet還是默認的TreeSet

兩者都不。 它是一個scala.collection.immutable.Set

這是scala.Array.toSet的文檔(實際上是scala.collection.IterableOnceOps.toSet ):

 def toSet[B >: A]: Set[B]

如您所見,它明確指定返回類型為Set

https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/immutable/Set.scala

最多 4 個元素EmptySetSet1 、 ...、 Set4 (如元組),然后是HashSet

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM