4

According to this posting, it is said that ListBuffer allows constant-time removal of the first and last elements. I've been looking into the API reference and the ListBuffer source code, but I can't find how I remove the last element in constant time while remove(0) will do the job for the first element. What would be the proper way to remove the last element?

Another question: is it possible to remove an element efficiently while iterating over a ListBuffer? In Java it can be done with Iterator.remove() but the Scala iterator doesn't seem to have the remove() method...

Community
  • 1
  • 1
K J
  • 4,505
  • 6
  • 27
  • 45

2 Answers2

1

The first question has an easy if disappointing answer: you can't remove the last element in constant time, as doing so would require a reference to the element-before-last. (It's a singly linked list, inside a wrapper class that holds the beginning and end elements of the list.)

The second question is equally easy and perhaps disappointing: Iterators in Scala are simply views of the collection. They don't modify the underlying collection. (This is in keeping with the "immutable by default, mutable only when necessary" philosophy.)

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • Thanks for the answer, Rex. So basically it'll always take O(n) of time to remove an arbitrary element from ListBuffer, won't it? It's quite disappointing that even with an iterator pointing to a specific element it's impossible to remove it right away :( – K J Oct 17 '12 at 06:43
1

You can remove the last element with trimEnd(1)

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198