gpt4 book ai didi

scala - HashSet 和 Set 有什么区别,应该什么时候使用?

转载 作者:行者123 更新时间:2023-12-04 02:36:54 25 4
gpt4 key购买 nike

HashSet有什么区别和 Set什么时候应该使用每一种?这是Map对比 HashMap :

val hashSet = HashSet("Tomatoes", "Chilies")
val set = Set("Tomatoes", "Chilies")
set == hashSet // res: Boolean = true

最佳答案

Set是一种特质。您可以创建 Set 的实例通过调用 apply其伴生对象的方法,该方法返回默认的不可变实例 Set .例如:

val defaultSet = Set("A", "B")
HashSetSet 的具体实现可以实例化如下:
val hashSet = HashSet("A", "B")

看看“Scala 编程”中的引用,它解释了各种实现之间的差异:

The scala.collection.mutable.Set() factory method, for example, returns a scala.collection.mutable.HashSet, which uses a hash table internally. Similarly, the scala.collection.mutable.Map() factory returns a scala.collection.mutable.HashMap.

The story for immutable sets and maps is a bit more involved. The class returned by the scala.collection.immutable.Set() factory method, for example, depends on how many elements you pass to it, as shown in the table below. For sets with fewer than five elements, a special class devoted exclusively to sets of each particular size is used, to maximize performance. Once you request a set that has five or more elements in it, however, the factory method will return an implementation that uses hash tries.


Number of elements  Implementation
0 scala.collection.immutable.EmptySet
1 scala.collection.immutable.Set1
2 scala.collection.immutable.Set2
3 scala.collection.immutable.Set3
4 scala.collection.immutable.Set4
5 or more scala.collection.immutable.HashSet

这意味着对于不可变的 Set对于 5 个或更多元素,您的两个调用都应返回相同 Set 的实例子类。
Map 也是如此s。见 this关联。

关于scala - HashSet 和 Set 有什么区别,应该什么时候使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18759913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com