我在第s = new Array(capacity)
行设置了一个断点,但似乎没有调用apply方法。我是否正确实施了它?
object StacksAndQueuesTest {
def main(args: Array[String]) {
val f = new FixedCapacityStackOfStrings(3)
println(f.isEmpty);
}
}
class FixedCapacityStackOfStrings(capacity : Int) {
var s : Array[String] = _
var N : Int = 0
def isEmpty : Boolean = {
N == 0
}
def push(item : String) = {
this.N = N + 1
s(N) = item
}
def pop = {
this.N = N - 1
val item : String = s(N)
/**
* Setting this object to null so
* that JVM garbage collection can clean it up
*/
s(N) = null
item
}
object FixedCapacityStackOfStrings {
def apply(capacity : Int){
s = new Array(capacity)
}
}
}
答案 0 :(得分:2)
在您的情况下,除了避免new
运算符
class FixedCapacityStackOfStrings(capacity: Int) {
var s: Array[String] = new Array(capacity)
var N: Int = 0
def isEmpty: Boolean = {
N == 0
}
def push(item: String) = {
this.N = N + 1
s(N) = item
}
def pop = {
this.N = N - 1
val item: String = s(N)
/**
* Setting this object to null so
* that JVM garbage collection can clean it up
*/
s(N) = null
item
}
}
object FixedCapacityStackOfStrings {
def apply(capacity: Int) = {
println("Invoked apply()")
new FixedCapacityStackOfStrings(capacity)
}
def main(args: Array[String]){
val f = FixedCapacityStackOfStrings(5)
println(f)
}
}
然后你可以像
一样使用它
val f = FixedCapacityStackOfStrings(5)
答案 1 :(得分:0)
对于调用对象'FixedCapacityStackOfStrings'来查看我需要使用的.isEmpty方法:
def apply(capacity: Int) : FixedCapacityStackOfStrings = {
new FixedCapacityStackOfStrings(capacity)
}
而不是
def apply(capacity: Int) {
new FixedCapacityStackOfStrings(capacity)
}