是否有特定的元素插入集合的顺序?
Is there a specific order of insertion of an element to a set?
当我试图将一个元素插入到 Scala 可变集时,我得到了以下输出。
我的代码如下。
object sets{
def main(args:Array[String]):Unit={
var set1 = Set(1,2,3,4);
println(set1);
println(set1.+(6));
}
}
输出如下。
Set(1,2,3,4)
Set(1,6,2,3,4)
在 1 之后而不是 4 之后打印 6 是否有特定原因?
集合中的顺序不取决于您何时插入元素。公平地说,集合中的顺序的想法并没有真正意义,因为集合是无序的集合。
如果您想了解为什么会看到这个顺序,这与对象的哈希码有关。我推荐阅读 Wikipedia article about Hashtables。
如果您需要保留插入对象的顺序,可以使用 List
。要保持集合中元素的唯一性,可以使用 List.distinct
。
LinkedHashSet
像这样保留插入顺序
val set1 = LinkedHashSet(1,2,3,4)
println(set1)
println(set1 += 6)
输出
LinkedHashSet(1, 2, 3, 4)
LinkedHashSet(1, 2, 3, 4, 6)
如解释的那样here
You need to preserve the order in which the items are inserted. Then
you use the LinkedHashSet
. Practically as fast as the normal HashSet
,
needs a little more storage space for the additional links between
elements.
注意LinkedHashSet
,和其他集合一样,不会保留重复项,即
assert(set1 == (set1 += 1)) // passes
如果您不需要元素的唯一性,请考虑使用 List
。
当我试图将一个元素插入到 Scala 可变集时,我得到了以下输出。
我的代码如下。
object sets{
def main(args:Array[String]):Unit={
var set1 = Set(1,2,3,4);
println(set1);
println(set1.+(6));
}
}
输出如下。
Set(1,2,3,4)
Set(1,6,2,3,4)
在 1 之后而不是 4 之后打印 6 是否有特定原因?
集合中的顺序不取决于您何时插入元素。公平地说,集合中的顺序的想法并没有真正意义,因为集合是无序的集合。
如果您想了解为什么会看到这个顺序,这与对象的哈希码有关。我推荐阅读 Wikipedia article about Hashtables。
如果您需要保留插入对象的顺序,可以使用 List
。要保持集合中元素的唯一性,可以使用 List.distinct
。
LinkedHashSet
像这样保留插入顺序
val set1 = LinkedHashSet(1,2,3,4)
println(set1)
println(set1 += 6)
输出
LinkedHashSet(1, 2, 3, 4)
LinkedHashSet(1, 2, 3, 4, 6)
如解释的那样here
You need to preserve the order in which the items are inserted. Then you use the
LinkedHashSet
. Practically as fast as the normalHashSet
, needs a little more storage space for the additional links between elements.
注意LinkedHashSet
,和其他集合一样,不会保留重复项,即
assert(set1 == (set1 += 1)) // passes
如果您不需要元素的唯一性,请考虑使用 List
。