美文网首页
Scala ListBuffer中+=操作理解

Scala ListBuffer中+=操作理解

作者: no0one | 来源:发表于2018-09-29 16:11 被阅读0次

    +=操作 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就是一串 :: 类链起来的.

    相关文章

      网友评论

          本文标题:Scala ListBuffer中+=操作理解

          本文链接:https://www.haomeiwen.com/subject/fehboftx.html