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

查看:15
本文介绍了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 是一个 trait,它的所有 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 中,您可以创建一个与您的类或 trait 同名的单例 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) 的语法糖.

**Set(x) is syntactic sugar for Set.apply(x).

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

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