HashSet 和 Set 有什么区别,应该什么时候使用? [英] what is the difference between HashSet and Set and when should each one be used?

查看:46
本文介绍了HashSet 和 Set 有什么区别,应该什么时候使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashSetSet 有什么区别,应该什么时候使用?这是 MapHashMap 的对比:

What is the difference between HashSet and Set and when should each one be used? Here's Map vs HashMap:

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

推荐答案

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

Set is a trait. You can create an instance of a Set by invoking apply method of its companion object, which returns an instance of a default, immutable Set. For example:

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

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

HashSet is a concrete implementation of a Set which can be instantiated as follows:

val hashSet = HashSet("A", "B")

查看Scala 编程"中解释各种实现之间差异的引用:

Have a look at the cite from "Programming in Scala" that explains the differences between various implementations:

scala.collection.mutable.Set() 工厂方法,例如,返回一个 scala.collection.mutable.HashSet,它使用一个哈希表内部.同样,scala.collection.mutable.Map() 工厂返回一个 scala.collection.mutable.HashMap.

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.

不可变集合和地图的故事有点复杂.这scala.collection.immutable.Set() 工厂方法返回的类,例如,取决于您传递给它的元素数量,如下表.对于少于五个元素的集合,使用专门用于每个特定大小的集合的特殊类,以最大化表现.一旦您请求一个包含五个或更多元素的集合但是,工厂方法将返回一个实现使用哈希尝试.

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,您的两个调用都应返回相同 Set 子类的实例.

It means that for an immutable Set with 5 or more elements, both of your calls should return an instance of the same Set subclass.

Map 也是如此.请参阅链接.

The same goes for Maps. See this link.

这篇关于HashSet 和 Set 有什么区别,应该什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆