Scala中"HashSet"和"Set"之间的区别? [英] The difference between 'HashSet' and 'Set' in Scala?

查看:325
本文介绍了Scala中"HashSet"和"Set"之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Scala的HashSetSet类型感到非常困惑,因为它们似乎都在做相同的事情.

I'm very confused by Scala's HashSet and Set types as they both seem to do the same thing.

  • 它们之间有什么区别?
  • 在Java中是否一样?
  • 在我的参考文献中,它说HashSet是一个显式集合类"(与Set相比).是什么意思?
  • What is the difference between them?
  • Is it the same in Java?
  • In my reference it says that HashSet is an "explicit set class" (as compared to Set). What does that mean?

推荐答案

Scala可变且不可变的HashSet实现是可以实例化的具体类.例如,如果您明确要求新的scala.collection.immutable.HashSet,则将始终获得由哈希树实现的集合.还有其他集合实现,例如ListSet,它使用列表.

Scala's mutable and immutable HashSet implementations are concrete classes which you can instantiate. For example, if you explicitly ask for a new scala.collection.immutable.HashSet, you will always get a set which is implemented by a hash trie. There are other set implementations, such as ListSet, which uses a list.

Set特征,所有已设置的实现都对此进行了扩展(而在Java中,Set是一个接口).

Set is a trait which all the set implementations extend (whereas in Java, Set is an interface).

Set也是带有apply **方法的伴侣对象*.调用Set(...)时,您将调用此工厂方法并获得返回值,该返回值是某种Set.它可能是HashSet,但可能是其他一些实现.根据 2 的规定,不可变集的默认实现对空集,并且集的大小最大为4.大小不小于5的不可变集和可变集都使用hashSet.

Set is also a companion object* with an apply** method. When you call Set(...), you're calling this factory method and getting a return value which is some kind of Set. It might be a HashSet, but could be some other implementation. According to 2, the default implementation for an immutable set has special representation for empty set and sets size up to 4. Immutable sets size 5 and above and mutable sets all use hashSet.

*在Scala中,可以使用与类或特征相同的名称来创建单例object,而不是使用静态类方法.这称为伴随对象,您在其上定义的方法可以称为ObjectName.method(),类似于您在Java中调用静态方法的方式.

*In Scala, instead of having static class methods, you can create a singleton object with the same name as your class or trait. This is called a companion object, and methods you define on it can be called as ObjectName.method(), similar to how you'd call a static method in Java.

** Set(x)Set.apply(x)的语法糖.

这篇关于Scala中"HashSet"和"Set"之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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