Scala 等效于 new HashSet(Collection)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/674545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala equivalent of new HashSet(Collection)
提问by oxbow_lakes
What is the equivalent Scala constructor (to create an immutableHashSet) to the Java
什么是Java的等效 Scala 构造函数(用于创建不可变的HashSet)
new HashSet<T>(c)
where cis of type Collection<? extends T>?.
c类型在哪里Collection<? extends T>?。
All I can find in the HashSetObjectis apply.
我能在HashSetObject 中找到的只是apply.
采纳答案by James Iry
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 : _*".
答案有两个部分。第一部分是采用 T* 的 Scala 可变参数方法是对采用 Seq[T] 的方法的补充。您告诉 Scala 将 Seq[T] 视为参数列表,而不是使用“seq:_*”的单个参数。
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.
第二部分是将 Collection[T] 转换为 Seq[T]。Scala 的标准库中目前还没有通用的内置方法,但一种非常简单(如果不一定有效)的方法是调用 toArray。这是一个完整的例子。
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)
Note the scala.Predef.Set and scala.collection.immutable.HashSet are synonyms.
注意 scala.Predef.Set 和 scala.collection.immutable.HashSet 是同义词。
回答by Fabian Steeg
The most concise way to do this is probably to use the ++operator:
最简洁的方法可能是使用++运算符:
import scala.collection.immutable.HashSet
val list = List(1,2,3)
val set = HashSet() ++ list

