This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Why am I getting 0-length ArrayBuffers?

1 reply
Ken McDonald
Joined: 2011-02-13,
User offline. Last seen 42 years 45 weeks ago.
scala> import scala.collection.mutable.ArrayBufferimport scala.collection.mutable.ArrayBuffer
scala> new ArrayBuffer[Int](3)res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> res1res2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> res1.lengthres3: Int = 0
This does not work at all like I would have thought reading the documentation.
ichoran
Joined: 2009-08-14,
User offline. Last seen 2 years 3 weeks ago.
Re: Why am I getting 0-length ArrayBuffers?
ArrayBuffer's constructor takes one argument--the length of the internal buffer that will initially be used to store the data.  It doesn't actually put anything in the buffer.

However, the companion object apply method takes anything you pass to it and makes an ArrayBuffer containing that.

So:

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> ArrayBuffer(3)  // This is the apply method on the companion
res0: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(3)

scala> new ArrayBuffer[Int](3) { def seeInside = array }
res1: scala.collection.mutable.ArrayBuffer[Int]{def seeInside: Array[AnyRef]} = ArrayBuffer()

scala> res1.seeInside
res2: Array[AnyRef] = Array(null, null, null)

  --Rex



On Thu, May 12, 2011 at 9:12 PM, Ken McDonald <ykkenmcd@gmail.com> wrote:
scala> import scala.collection.mutable.ArrayBufferimport scala.collection.mutable.ArrayBuffer
scala> new ArrayBuffer[Int](3)res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> res1res2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> res1.lengthres3: Int = 0
This does not work at all like I would have thought reading the documentation.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland