Android Question index out of bounds

Discussion in 'Android Questions' started by coder19075, Jun 27, 2017.

  1. coder19075

    coder19075 New Member

    I'm getting a bug on just trying to increment an integer.

    The error is: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2

    Here is the code to reproduce:

    Code:
    Dim lst As List
    lst.Initialize
    Dim obj1 As Map
    obj1.Initialize
    obj1.Put(
    "id"888)
    Dim obj2 As Map
    obj2.Initialize
    obj2.Put(
    "id"999)
    Dim obj3 As Map
    obj3.Initialize
    obj3.Put(
    "id"999)
    lst.Add(obj1)
    lst.Add(obj2)
    lst.Add(obj3)

    Dim lst2 As List
    lst2.Initialize

    For Each p As Map In lst
        
    Dim i As Int = 0
        
    For Each p2 As Map In lst
            
    If p.Get("id") = p2.Get("id"Then
                lst.RemoveAt(i)
            
    End If
            i = i + 
    1 'error in this line
        Next
        lst2.Add(p)
    Next
     
    Last edited: Jun 27, 2017
  2. Erel

    Erel Administrator Staff Member Licensed User

    Moved to the questions forum. It is not a bug.

    You shouldn't modify the list from inside a For Each block that iterates over the list items.

    What are you trying to implement?
     
  3. An Schi

    An Schi Well-Known Member Licensed User

    Had this confusing me as well ;)

    When you want to have index 2 the size should be 3 (index 0, index 1 and index 2).
     
  4. coder19075

    coder19075 New Member

    "You shouldn't modify the list from inside a For Each block that iterates over the list items."

    Why?

    I'm trying to remove duplicates from a list.
     
    Last edited: Jun 28, 2017
  5. eurojam

    eurojam Well-Known Member Licensed User

    try this:
    Code:
    Dim obj1 As Map
    obj1.Initialize
    obj1.put(
    888,"")
    obj1.put(
    999,"")
    obj1.put(
    999,"")

    Dim lst As List
    lst.Initialize
    For Each k As Int In obj1.Keys
        lst.add(k)
    Next
    Log(lst)
     
  6. eps

    eps Well-Known Member Licensed User

    Think about it.

    The For Loop thinks that it's dealing with 4 items... You remove 2 inside the loop and it will hit the end of the loop before it expects to and then give an Out of Bounds Exception.

    Ideally only move non-duplicates to a new list.
     
  7. eps

    eps Well-Known Member Licensed User

  8. coder19075

    coder19075 New Member

    Thanks, that was helpful
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice