2

I need to add to an array two strings, omitting the first occurrence:

  val strings = ArrayBuffer[String]()

  strings(1) = "abc1"
  strings(2) = "abc2"

But I'm getting

  Exception in thread "main" java.lang.IndexOutOfBoundsException: 1

How to fix this?

4
  • Possible duplicate of Initialize data structure in Scala Commented Jun 20, 2016 at 11:34
  • This is more or less the same question as your previous question. You first need to add elements to the ArrayBuffer before you can modify the elements at specific indices. Commented Jun 20, 2016 at 11:35
  • but I can't add elements with += as I need to set them with an index Commented Jun 20, 2016 at 11:35
  • If you know how big your array needs to be (which the need to use an index suggests), then use an Array of the right size, not an ArrayBuffer. Commented Jun 20, 2016 at 12:51

1 Answer 1

2

Your ArrayBuffer is empty, so you cannot set an element at index i to a new String - index i is not a valid index if the ArrayBuffer is empty. First make sure the elements exist in the ArrayBuffer by adding them:

val strings = ArrayBuffer[String]()

strings += "abc1"
strings += "abc2"

Now the ArrayBuffer has two elements and you can modify them if you want. Note that indices start at 0, not at 1.

strings(0) = "something else"
strings(1) = "hello world"

If you want to pre-fill the ArrayBuffer you can for example use fill, as I showed you in my answer to your previous question.

// Fill with 10 empty strings (creates 10 elements in the ArrayBuffer)
val strings = ArrayBuffer.fill(10) { "" }

// Now you can set them (valid indices are 0...9)
strings(0) = "abc1"
strings(1) = "abc2"

Alternatively, use a Map instead of an ArrayBuffer, where the keys of your map are numbers and the values are strings.

import scala.collection.mutable.Map

val strings: Map[Int, String] = Map()

strings(1) = "abc1"
strings(2) = "abc2"
Sign up to request clarification or add additional context in comments.

2 Comments

There's no way to set the occurrences by index?
@ps0604 What do you mean? If you use an ArrayBuffer, then the element at the specified index must exist before you can modify it. See also my alternative solution with a Map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.