-1

我在 line 处设置了一个断点,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)
  }
}

}
4

2 回答 2

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)

于 2013-04-10T20:25:21.877 回答
0

对于调用对象 'FixedCapacityStackOfStrings' 来查看我需要使用的 .isEmpty 方法:

  def apply(capacity: Int) : FixedCapacityStackOfStrings = {
    new FixedCapacityStackOfStrings(capacity)
  }

代替

  def apply(capacity: Int) {
    new FixedCapacityStackOfStrings(capacity)
  }
于 2013-04-10T22:17:43.987 回答