加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – HashSet和Set之间有什么区别,何时应该是每个

发布时间:2020-12-16 19:04:24 所属栏目:安全 来源:网络整理
导读:HashSet和Set之间有什么区别,何时应该使用?这里的地图vs HashMap: val hashSet = HashSet("Tomatoes","Chilies")val set = Set("Tomatoes","Chilies")set == hashSet // res: Boolean = true 解决方法 集是一个特质.您可以通过调用其伴随对象的apply方法来
HashSet和Set之间有什么区别,何时应该使用?这里的地图vs HashMap:

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

解决方法

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

val defaultSet = Set("A","B")

HashSet是一个具体的实现,可以实例化如下:

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

这意味着对于具有5个或更多元素的不可变集合,您的两个调用都应该返回同一个Set子类的实例.

地图同样如此.请参阅this链接.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读