title: Large array indexes scala
body: <p>(Language: scala)</p>
  
  <p>I have a problem where I want to iterate over 1 million numbers, but for some reason I get an arrayindexOutofbounds exception. The function I am using works perfectly for 100 000 numbers, but I get the exception if I add a zero. </p>
  
  <p>There cannot be a problem with the array size, because I have built a sort of flex-array, where the array is about 1000 elements and each element consists of a list of elements. </p>
  
  <p>So the problem looks something like this: </p>
  
  <pre><code>for (x &lt;- 1 to 1000000) {
    // Do a thing
    }     
  </code></pre>
  
  <p>Can for loops only handle a certain number of elements?</p>
  
  <p>I have tried running the program with the "extra-space-flag" </p>
  
  <p>I include the whole code below for reference, in case it makes a difference</p>
  
  <pre><code>object Problem14 {
  
    class FlexArray (n : Int){
      var array = new Array[List[Tuple2[Int, Int]]](n)
      val size = n
  
      for(x &lt;- 0 until size) {
        array(x) = List()
      }
  
      def insert (n : Int, value : Int) {
        if (find(n) != -1) {
       val i = n % size
       array(i) = (n, value) :: array(i)
        }
      }
  
      def read (i : Int) : List[Tuple2[Int, Int]] = {
        (array(i))
      }
  
      def findAux (list : List[Tuple2[Int, Int]], n : Int) : Int = {
        if (list == Nil) {
      -1
        } else {
      val (num, value) = list.head
      if (n == num) {
        value
      } else {
        findAux(list.tail, n)
      }
        }
      }
  
      def find (n : Int) : Int = {
        val i = n % size
        findAux(array(i), n)
      }
    }
  
    var accArray = new FlexArray(10000)
  
  
  // denna funktion bör kallas med 1 som andra argument
    def chainLength (n : Int, acc : Int) : Int = {
      if (n == 1) 
        acc
      else {
        val value = accArray.find(n)
      if (value != -1) 
    acc + value 
      else if (n % 2 == 0)
    chainLength(n/2, acc+1)
      else
    chainLength(3*n+1, acc+1)      
      }
    }
  
  
  
   def main(args: Array[String]) {
      var max = 0
      var maxnum = 0
  
      for (x &lt;- 1 to 1000000) {
        var value = chainLength(x, 1)
        accArray.insert(x, value)
        if (max &lt; value) { 
      max = value
      maxnum = x
        }      
  
      println(maxnum + ": " + max)
  
  }
  </code></pre>
  
  <p>}</p>