5

For example suppose I want a list that contains 0 up to a max of 1000 elements. Above this, the oldest insertions should be dropped first. Do collections support this functionality natively? If not how would I go about the implementation? I understand that certain operations are very slow on Lists so maybe I need a different data type?

Looking at an element should not affect the list. I would like insert and size operations only.

deltanovember
  • 42,611
  • 64
  • 162
  • 244
  • 1. Do you remove a (regular) element of the list when you look at it ? (I'm looking at size-bounded queues) 2. Do you have an idea of the operations you *do* need ? – Francois G Aug 15 '11 at 03:58
  • Amended with extra information – deltanovember Aug 15 '11 at 04:53
  • Don't you need to *look* at list elements ? At all ? If so, do you want to start looking at the head of the list (the last one you entered ?), the tail (the oldest element ?) or any element, accessed through its index ? – Francois G Aug 15 '11 at 05:01
  • I don't need to look at the elements. Once per day I need to do a sort and then I look at the highest ranking. Before that I do many many inserts and so I need this portion to be very efficient. – deltanovember Aug 15 '11 at 05:10

4 Answers4

9

It sounds like you want a size-bounded queue. Here's a similar question: Maximum Length for scala queue

There are three solutions presented in that question. You can,

  1. Write a queue from scratch (paradigmatic gave code for this),
  2. Extend Scala's Queue implementation by subclassing, or
  3. Use the typeclass extension pattern (aka, "pimp my library") to extend Scala's Queue.
Community
  • 1
  • 1
Kipton Barros
  • 21,002
  • 4
  • 67
  • 80
9

Here is my first pass implementation in case someone else find it useful

import scala.collection._
import mutable.ListBuffer

class FixedList[A](max: Int) extends Traversable[A] {

  val list: ListBuffer[A] = ListBuffer()

  def append(elem: A) {
    if (list.size == max) {
      list.trimStart(1)
    }
    list.append(elem)
  }

  def foreach[U](f: A => U) = list.foreach(f)

}
deltanovember
  • 42,611
  • 64
  • 162
  • 244
1

A circular array is the fastest implementation. It's basically an array with a read and write index which are wrapped when reaching the end of the array. Size is defined as:

def size = writeIndex - readIndex + (if (readIndex > writeIndex) array.size else 0)
Jesper Nordenberg
  • 2,104
  • 11
  • 15
0

While not an answer to the question's details (but does somewhat answer the question's title), List.fill(1000){0} would create a List of length 1000 with initial value of 0, which is from

Scala - creating a type parametrized array of specified length

Marcus
  • 2,128
  • 20
  • 22