ArrayBuffer
Introduction to ArrayBuffer
- Overview: An
ArrayBufferis a mutable indexed sequence that allows you to append, prepend, insert, and remove elements efficiently. It is part of the Scala Collections Library. - Importing
ArrayBuffer:import scala.collection.mutable.ArrayBuffer - Creating an
ArrayBuffer:val nums = ArrayBuffer[Int]() // Or new ArrayBuffer[Int] val strings = ArrayBuffer("one", "two", "three")
Adding Elements
- Appending Elements: Use
+=to append one or more elements at the end.nums += 4 nums += (5, 6, 7) - Prepending Elements: Use
+=:orprependto add elements at the start.3 +=: nums nums.prepend(1, 2) - Inserting Elements: Use
insertto add elements at a specific index.nums.insert(2, 8) // Inserts 8 at index 2
Removing Elements
- Removing by Index: Use
removeto delete elements at a specific index.nums.remove(2) // Removes the element at index 2 - Removing Multiple Elements: Specify the index and the number of elements to remove.
nums.remove(0, 3) // Removes 3 elements starting from index 0 - Clearing All Elements: Use
clearto empty the entire buffer.nums.clear()
Accessing and Updating Elements
- Accessing Elements: Use the
applymethod or parentheses.val firstElement = nums(0) - Updating Elements: Assign a new value to a specific index.
nums(0) = 10
Common Operations
- Iterating Over Elements: Use
foreach,forloops, or higher-order functions.nums.foreach(println) - Transforming
ArrayBuffer: Usemap,filter, etc., to produce new collections.val doubledNums = nums.map(_ * 2) - Converting to Arrays: Use
toArrayfor a fixed-size representation.val numsArray = nums.toArray
Performance Considerations
- Amortized Costs: While append operations are generally efficient, be mindful of the amortized cost of resizing, especially for very large collections.
- Memory Overhead:
ArrayBufferuses more memory than a plain array due to its resizable nature.
Use Cases for ArrayBuffer
- When to Use:
ArrayBufferis ideal for building up sequences of elements when the number of elements is unknown upfront or when frequent updates to the sequence are required. - Comparisons: Prefer
ArrayBufferover immutable collections when mutability is necessary for performance reasons, but choose immutable collections when mutability is not a requirement to leverage functional programming benefits.