Maximum Length for scala queue

后端 未结 4 1497
死守一世寂寞
死守一世寂寞 2020-12-09 04:55

I\'m curious if Scala has some gem hidden in its collection classes that I can use. Basically I\'m looking for something like a FIFO queue, but that has an upper-limit on i

4条回答
  •  臣服心动
    2020-12-09 05:17

    This is the approach I toke with extending Scala's standard mutable.Queue class.

    class LimitedQueue[A](maxSize: Int) extends mutable.Queue[A] {
      override def +=(elem: A): this.type = {
        if (length >= maxSize) dequeue()
        appendElem(elem);
        this
      }
    }
    

    And simple use-case

    var q2 = new LimitedQueue[Int](2)
    q2 += 1
    q2 += 2
    q2 += 3
    q2 += 4
    q2 += 5
    
    q2.foreach { n =>
      println(n)
    }
    

    You'll get only 4 and 5 in the console as the old elements were dequeued beforehand.

提交回复
热议问题