Public Sub ClearOBList
For Each key As String In xassets.Keys 'xassets is just a map
If key.Contains("-ob-") Then
xassets.Remove(key)
End If
Next
End Sub
and getting this error: java.util.ConcurrentModificationException
I'm guessing it hasn't finished removing the last key before trying to remove the current key...?
Anybody have an idea? Maybe there's a better way to remove these keys?
1. You can use B4XOrderedMap and then iterate over the keys in reverse order. This is better than using Map.GetKeyAt which isn't built for this and will have an impact on performance if the map is large.
2. Another option that I usually do is:
B4X:
Dim KeysToRemove As List
KeysToRemove.Initialize
For Each key As String In Map.Keys
If key.Contains("something") Then KeysToRemove.Add(key)
Next
For Each Key As String In KeysToRemove
Map.Remove(Key)
Next
Public Sub ClearOBList
For Each key As String In xassets.Keys 'xassets is just a map
If key.Contains("-ob-") Then
xassets.Remove(key)
End If
Next
End Sub
and getting this error: java.util.ConcurrentModificationException
I'm guessing it hasn't finished removing the last key before trying to remove the current key...?
Anybody have an idea? Maybe there's a better way to remove these keys?
Since keys are unique, there can only be one "-ob-", exit the loop when you find it.
B4X:
Public Sub ClearOBList
For Each key As String In xassets.Keys 'xassets is just a map
If key.Contains("-ob-") Then
xassets.Remove(key)
Exit ' <---
End If
Next
End Sub
@LucaMs re "Since keys are unique, there can only be one "-ob-", exit the loop when you find it." : yes but there can be an "-ob-1" and an "-ob-2" and an "-ob-wan-kenobi"
This does the trick:
B4X:
Public Sub ClearOBList
Dim foundKey As Boolean = True
Do While foundKey
foundKey = False
For Each key As String In xassets.Keys 'xassets is just a map
If key.Contains("-ob-") Then
xassets.Remove(key)
foundKey = True
End If
Next
Loop
End Sub
1. You can use B4XOrderedMap and then iterate over the keys in reverse order. This is better than using Map.GetKeyAt which isn't built for this and will have an impact on performance if the map is large.
2. Another option that I usually do is:
B4X:
Dim KeysToRemove As List
KeysToRemove.Initialize
For Each key As String In Map.Keys
If key.Contains("something") Then KeysToRemove.Add(key)
Next
For Each Key As String In KeysToRemove
Map.Remove(Key)
Next
@LucaMs re "Since keys are unique, there can only be one "-ob-", exit the loop when you find it." : yes but there can be an "-ob-1" and an "-ob-2" and an "-ob-wan-kenobi"
This does the trick:
B4X:
Public Sub ClearOBList
Dim foundKey As Boolean = True
Do While foundKey
foundKey = False
For Each key As String In xassets.Keys 'xassets is just a map
If key.Contains("-ob-") Then
xassets.Remove(key)
foundKey = True
End If
Next
Loop
End Sub