From ef8360f243d7d840437f3383971898a66bf758c2 Mon Sep 17 00:00:00 2001 From: chrisokasaki Date: Tue, 30 Aug 2016 23:46:31 -0400 Subject: SI-9906: override ListBuffer.last/lastOption to run in O(1) time Also update scaladocs for those two methods. --- src/library/scala/collection/mutable/ListBuffer.scala | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/library/scala/collection/mutable/ListBuffer.scala b/src/library/scala/collection/mutable/ListBuffer.scala index 02fcced3ac..3bb7004184 100644 --- a/src/library/scala/collection/mutable/ListBuffer.scala +++ b/src/library/scala/collection/mutable/ListBuffer.scala @@ -386,6 +386,25 @@ final class ListBuffer[A] this } + /** Selects the last element. + * + * Runs in constant time. + * + * @return the last element of this buffer. + * @throws NoSuchElementException if this buffer is empty. + */ + override def last: A = + if (last0 eq null) throw new NoSuchElementException("last of empty ListBuffer") + else last0.head + + /** Optionally selects the last element. + * + * Runs in constant time. + * + * @return `Some` of the last element of this buffer if the buffer is nonempty, `None` if it is empty. + */ + override def lastOption: Option[A] = if (last0 eq null) None else Some(last0.head) + /** Returns an iterator over this `ListBuffer`. The iterator will reflect * changes made to the underlying `ListBuffer` beyond the next element; * the next element's value is cached so that `hasNext` and `next` are -- cgit v1.2.3