【发布时间】:2016-12-11 21:15:47
【问题描述】:
有两种方法可以获取随机访问 Scala 集合(例如 Vector)的第一个元素:
1) 头部
myCollction.head
2) 申请
myCollction(0)
根据我收集到的信息(来自 Scala 2.10.4 源代码)
-
head首先检查集合是否为空,并在调用apply(0)之前抛出异常
override /*IterableLike*/ def head: A = { if (isEmpty) throw new UnsupportedOperationException("empty.head") apply(0) } -
apply 先检查索引的边界,在获取元素之前抛出 IndexOutOfBoundsException
def apply(index: Int): A = { val idx = checkRangeConvert(index) getElem(idx, idx ^ focus) } private def checkRangeConvert(index: Int) = { val idx = index + startIndex if (0 <= index && idx < endIndex) idx else throw new IndexOutOfBoundsException(index.toString) }
首选方式是什么? (实际的好处/陷阱,不是个人喜好)
【问题讨论】: