问题描述
什么是等效的Scala构造函数(用于创建不可变 HashSet
)到Java
What is the equivalent Scala constructor (to create an immutable HashSet
) to the Java
new HashSet<T>(c)
其中 c
的类型为 Collection<?扩展T>
?。
我可以在 HashSet中找到
对象是 apply
。
推荐答案
有两个部分回答。第一部分是采用T *的Scala变量参数方法是采用Seq [T]的方法。您告诉Scala使用seq:_ *将Seq [T]视为参数列表而不是单个参数。
There are two parts to the answer. The first part is that Scala variable argument methods that take a T* are a sugaring over methods taking Seq[T]. You tell Scala to treat a Seq[T] as a list of arguments instead of a single argument using "seq : _*".
第二部分是将Collection [T]转换为Seq [T]。在Scala的标准库中还没有通用的内置方法,但是一种非常简单(如果不一定有效)的方法是通过调用toArray。这是一个完整的例子。
The second part is converting a Collection[T] to a Seq[T]. There's no general built in way to do in Scala's standard libraries just yet, but one very easy (if not necessarily efficient) way to do it is by calling toArray. Here's a complete example.
scala> val lst : java.util.Collection[String] = new java.util.ArrayList
lst: java.util.Collection[String] = []
scala> lst add "hello"
res0: Boolean = true
scala> lst add "world"
res1: Boolean = true
scala> Set(lst.toArray : _*)
res2: scala.collection.immutable.Set[java.lang.Object] = Set(hello, world)
注意scala.Predef.Set和scala.collection.immutable.HashSet是同义词。
Note the scala.Predef.Set and scala.collection.immutable.HashSet are synonyms.
这篇关于Scala相当于新的HashSet(Collection)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!