ArrayStack移除方法?
ArrayStack
类中是否有与 Java 的 remove
功能相同的方法? 或者可以用 Scala 写一个吗?
Is there a method that does the same as Java's remove
in the ArrayStack
class?
Or is it possible to write one in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所有 Scala 的集合类型都支持在开头或结尾添加/删除元素(具有不同的性能权衡),并且大小仅受 JVM 的某些属性的限制 - 例如指针的最大大小。
因此,如果这是您使用 Stack 的唯一原因,那么您选择了错误的集合类型。考虑到能够从集合中间删除元素的要求,像
Vector
这样的东西更适合。All Scala's collection types support adding/removing elements at either the start or the end (with varying performance trade-offs), and are only limited in size by certain properties of the JVM - such as the maximum size of pointers.
So if this is the only reason that you're using a
Stack
, then you've chosen the wrong collection type. Given the requirement to be able to remove elements from the middle of the collection, something like aVector
would be a much better fit.您可以使用
filterNot(_ == o)
创建另一个缺少任何o
实例的堆栈(至少在 2.9 中),并且您可以stack.slice (0,n) ++ stack.slice(n+1,stack.length)
创建一个缺少索引元素的新堆栈。但是,不,没有确切的模拟,可能是因为删除数组中随机位置的项目是一件低性能的事情。
编辑:实际上,在 2.9.0.RC2 中,
slice
对我来说似乎有问题(我已经提交了一份错误报告,其中包含修复它的代码,因此大概会在 2.9.0.final 中修复此问题) 。在 2.8.1 中,您必须手动创建一个新的 ArrayStack。所以我想现在的答案是非常明确的“不”。编辑:
slice
已修复,因此从 2.9.0.RC4 及更高版本开始,切片方法应该可以工作。You can use
filterNot(_ == o)
to create another stack with any instances ofo
missing (at least in 2.9), and you canstack.slice(0,n) ++ stack.slice(n+1,stack.length)
to create a new stack with in indexed element missing.But, no, there isn't an exact analog, probably because removing an item at a random position in an array is a low-performance thing to do.
Edit:
slice
seems buggy to me, actually, in 2.9.0.RC2 (I have filed a bug report with code to fix it, so this will be fixed for 2.9.0.final, presumably). And in 2.8.1, you have to create a newArrayStack
by hand. So I guess the answer for now is a pretty emphatic "no".Edit:
slice
has been fixed, so as of 2.9.0.RC4 and later, the slice approach should work.也许这可以满足您的需求:
或者还有 Stack 类的不可变版本。
Maybe this could fit your needs:
Or there is also immutable version of the Stack class.