Reputation: 165
Let suppose that i create ArrayBuffer with initial size equal 10
val buf = new ArrayBuffer[Int](10)
If i did call to method buf.size - got the size of buffer equal 0?
Upvotes: 3
Views: 11245
Reputation: 3174
To initialize an arraybuffer with given size and value:
ArrayBuffer.fill(10)(5)
which will get:
scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5, 5, 5, 5, 5, 5, 5, 5, 5, 5)
Upvotes: 3
Reputation: 32335
The array buffer class is meant to be an extensible array in which you can efficiently add elements at the end using +=
. Initially, when created, the number of elements is 0 - that is referred to as the size
of the collection.
Internally, the array buffer maintains an array of elements, which contains only null
s when the buffer is created. Once an element is added, a write occurs into the array. When the array gets full, a new array with a double length is allocated and elements are copied into it. The amortized time of adding an element remains O(1).
The ctor argument simply says what the initial length of the internal array will be. Although changing the initial length does not change the amortized cost of +=
it can avoid unnecessary reallocations if you know how many elements you will add to it, thus being more efficient (in essence, decreasing the constant in the amortized analysis).
This argument is referred to as not the size, but as the capacity of the array buffer.
Upvotes: 11
Reputation: 11308
Using http://www.simplyscala.com/:
import scala.collection.mutable.ArrayBuffer
val buf = new ArrayBuffer[Int](10)
buf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
buf.size
res0: Int = 0
buf.length
res1: Int = 0
So I guess, the answer is not 10.
Upvotes: 2
Reputation: 5426
Yes, because size
(in this case inherited from IndexedSeq
) refers to the number of elements in a collection, not the size or length of the underlying data structure.
Upvotes: 5