+=操作 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
}
在上面的語(yǔ)句中胆建,將last0賦值給start曼尊,以及將last0賦值給val對(duì)象last1重挑,是關(guān)鍵囚似。此時(shí),只要對(duì)last1的tl(即tail顾画,聲明為var的scala包下可訪問(wèn)的構(gòu)造函數(shù)參數(shù))進(jìn)行賦值翎迁,其實(shí)就是給start增加尾部元素。
當(dāng)ListBuffer為空時(shí)叨咖,start一開始就指向了第一個(gè)創(chuàng)建的 :: 類,然后每加入一個(gè)單元就創(chuàng)建一個(gè) :: 類啊胶,依次用tl鏈起來(lái)甸各;整個(gè)start就是一串 :: 類鏈起來(lái)的.