Is there a method that does the same as Java's remove
in the ArrayStack
class?
Or is it po开发者_如何学JAVAssible to write one in Scala?
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 a Vector
would be a much better fit.
You can use filterNot(_ == o)
to create another stack with any instances of o
missing (at least in 2.9), and you can stack.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 new ArrayStack
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.
Maybe this could fit your needs:
scala> import collection.mutable.Stack
import collection.mutable.Stack
scala> val s = new Stack[Int]
s: scala.collection.mutable.Stack[Int] = Stack()
scala> s push 1
res0: s.type = Stack(1)
scala> s push 2
res1: s.type = Stack(2, 1)
scala> s push 3
res2: s.type = Stack(3, 2, 1)
scala> s pop
res3: Int = 3
scala> s pop
res4: Int = 2
scala> s pop
res5: Int = 1
Or there is also immutable version of the Stack class.
精彩评论