Android Question index out of bounds

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:

B4X:
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:

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?
 

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).
 

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:

eurojam

Well-Known Member
Licensed User
try this:
B4X:
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)
 

eps

Well-Known Member
Licensed User
"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.
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.
 
Top