Scala 可变集合中的 HashSet 类支持 update 方法。
但是,名称update
似乎违反直觉(至少对我来说)。来自文档here它说
This method allows one to add or remove an element elem from this set depending on the value of parameter included. Typically, one would use the following syntax: set(elem) = true
我尝试在 scala 控制台上使用 update
。当我调用 update(elem, true)
而不是使用新版本更新 elem 时,当元素存在时它什么也不做。
当 update(elem, false) 时,它删除了 elem。
我的问题是 update
方法的目的是什么,因为它不更新
任何内容
最佳答案
我认为更新是针对集合而不是集合中的元素(“更新”元素没有意义,它只对具有键值关系的集合有意义),并且事实上,如果你查看源代码,这个方法确实会更新集合:
def update(elem: A, included: Boolean) {
if (included) this += elem else this -= elem
}
所以基本上你可以使用 included
变量来告诉是否添加或删除一个元素,在你的情况下添加两次相同的元素不会给你任何更新,因为集合不允许重复。
为什么人们会使用update
而不是add
或remove
,这超出了我的理解范围。
关于java - Scala 中可变 HashSet 类的更新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074003/