Bug? For Each Bug or Feature?

agraham

Expert
Licensed User
Longtime User
This is the hoary old problem of iterating and deleting from a collection.
Erel may or may not consider this a bug!
Intuitively I expect the following to work on a Map but it errors with a NoSuchElementException.
I assume because B4A Map is not a pure Map but has some internal indexing code.
B4X:
        Dim ViewsMap As Map
        ...
        For Each dv As DraggableView In ViewsMap.keys
            Dim v As View
            v = dv.dView
            v.RemoveView
            ViewsMap.Remove(dv)         
        Next
 
Last edited:

Salar82

Member
try this:


B4X:
Dim ViewsMap As Map
        
For Each dv As View In ViewsMap.keys
    If dv Is DraggableView Then
        Dim v As View
        v = dv.dView
        v.RemoveView
        ViewsMap.Remove(dv)
    End If       
Next
 

agraham

Expert
Licensed User
Longtime User
Nope - that's nothing to do with the problem. All the keys are DraggableViews. The problem is an interaction between the compiled code, which produces a Java for(...) loop with a fixed number of iterations and some internal indexing added to the B4A Map. For reference the answer in this case is to clear the Map outside the loop, but there may be occasions when you want to keep some items.
B4X:
        For Each dv As DraggableView In ViewsMap.keys
            Dim v As View
            v = dv.dView
            v.RemoveView
        Next
        ViewsMap.Clear
 

agraham

Expert
Licensed User
Longtime User
You are not allowed to modify the collection while inside a For Each loop.
OK. I guess then if you want to delete only some items in a collection you would need to copy the ones to keep to a new Map and assign it to the old variable after the loop. Or do you have a better idea?
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…