+=操作 Appends a single element to this buffer. This operation takes constant time.
源码:
def += (x: A): this.type = {
if (exported) copy()
if (isEmpty) {
last0 = new :: (x, Nil)
start = last0
} else {
val last1 = last0
last0 = new :: (x, Nil)
last1.tl = last0
}
len += 1
this
}
在上面的语句中,将last0赋值给start,以及将last0赋值给val对象last1,是关键。此时,只要对last1的tl(即tail,声明为var的scala包下可访问的构造函数参数)进行赋值,其实就是给start增加尾部元素。
当ListBuffer为空时,start一开始就指向了第一个创建的 :: 类,然后每加入一个单元就创建一个 :: 类,依次用tl链起来;整个start就是一串 :: 类链起来的.
网友评论