Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ArrayBuffer







Introduction to ArrayBuffer

  • Overview: An ArrayBuffer is 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 +=: or prepend to add elements at the start.
    3 +=: nums
    nums.prepend(1, 2)
    
  • Inserting Elements: Use insert to add elements at a specific index.
    nums.insert(2, 8)  // Inserts 8 at index 2
    







Removing Elements

  • Removing by Index: Use remove to 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 clear to empty the entire buffer.
    nums.clear()
    







Accessing and Updating Elements

  • Accessing Elements: Use the apply method 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, for loops, or higher-order functions.
    nums.foreach(println)
    
  • Transforming ArrayBuffer: Use map, filter, etc., to produce new collections.
    val doubledNums = nums.map(_ * 2)
    
  • Converting to Arrays: Use toArray for 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: ArrayBuffer uses more memory than a plain array due to its resizable nature.







Use Cases for ArrayBuffer

  • When to Use: ArrayBuffer is 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 ArrayBuffer over immutable collections when mutability is necessary for performance reasons, but choose immutable collections when mutability is not a requirement to leverage functional programming benefits.