Vlad
Vlad

Reputation: 33

IndexOutOfBoundsException Error Vector In Scala

I am receiving the following error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: -1
at scala.collection.immutable.Vector.checkRangeConvert(Vector.scala:132)
at scala.collection.immutable.Vector.apply(Vector.scala:122)

This means that I am out of memory? How can i fix it?

Upvotes: 0

Views: 2855

Answers (2)

prayagupadhyay
prayagupadhyay

Reputation: 31262

you get IndexOutOfBoundsException, when you try to access an index greater than number of elements in a collection or less than 0 as the vector starts from index 0.

example below,

scala> val vector = Vector("washington", "iowa", "california")
vector: scala.collection.immutable.Vector[String] = Vector(washington, iowa, california)

scala> vector(0)
res4: String = washington

scala> vector(1)
res5: String = iowa

scala> vector(2)
res6: String = california

you get IndexOutOfBoundsException if you try to access index < 0 or index >=3,

scala> vector(3)
java.lang.IndexOutOfBoundsException: 3
  at scala.collection.immutable.Vector.checkRangeConvert(Vector.scala:132)
  at scala.collection.immutable.Vector.apply(Vector.scala:122)
  ... 33 elided

how can i fix it?

check if the index you are accessing is lesser than 0 or greater than number of elements in a vector or use .lift on collection.

scala> vector.lift(0)
res14: Option[String] = Some(washington)

scala> vector.lift(3)
res15: Option[String] = None

releated question - How to get an Option from index in Collection in Scala?

Upvotes: 4

Tyler
Tyler

Reputation: 18187

You are trying to access the -1th element of your vector. In Scala there are not circular indexes like in some other languages, so you are only allowed to specify positive indexes (and zero). Here is an example:

val v = Vector("a", "b", "c")
v: scala.collection.immutable.Vector[String] = Vector(a, b, c)

scala> v(0)
res1: String = a

scala> v(1)
res2: String = b

scala> v(-1)
java.lang.IndexOutOfBoundsException: -1
  at scala.collection.immutable.Vector.checkRangeConvert(Vector.scala:123)
  at scala.collection.immutable.Vector.apply(Vector.scala:114)

As you can see, when I specify the indexes 0 or 1 everything is fine, but when I try -1 I get the same error you are seeing. The error not in how you are accessing the vector, but the part of the vector you are trying to access.

Upvotes: 2

Related Questions