K J
K J

Reputation: 4743

Removing elements from ListBuffer

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...

Upvotes: 4

Views: 1220

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74048

You can remove the last element with trimEnd(1)

Upvotes: 1

Rex Kerr
Rex Kerr

Reputation: 167891

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.)

Upvotes: 1

Related Questions