Android Question List Element Removal - Can Anyone Help?

wonder

Expert
Licensed User
Longtime User
Good morning!

So, I have the following algorithm:
- Iterate through every element of a list
- Check element status
- If "good", do something, if otherwise "bad", remove it from the list.


In my first attempt, I wrote:
B4X:
For Each Element As MyCustomClass in ThisList
    If Element.isFineThankYou Then Element.Enjoy Else ThisList.RemoveAt(ThisList.IndexOf(Element))
Next
This didn't work because with each removal, the list changes size and due to that fact, I eventually got out of bounds (crash!).

As soon as I understood it, I came-up with the following solution:
B4X:
Dim RemovalList As List
RemovalList.Initialize

For Each Element As MyCustomClass In ThisList
    If Element.isFineThankYou Then Element.Enjoy Else RemovalList.Add(Element)
Next

For Each Element As MyCustomClass In RemovalList
    ThisList.RemoveAt(ThisList.IndexOf(Element))
Next

RemovalList.Clear

It works like a charm, but in my view, it's pretty ugly having to use two lists...

How can I improve this code by using only one list?
There must be a really simple way to do it...
 
Last edited:

Widget

Well-Known Member
Licensed User
Longtime User
You are over thinking things.
Use a simple loop:

B4X:
private Ndx as Int
private Element as MyCustomClass

'Traverse the loop backwards so items are deleted from the end of the List
for Ndx=ThisList.Size-1 to 0 step -1
  Element= ThisList.Get(Ndx)
  if (Element.IsInitialized=False) or (Element.isFineThankYou=False) then
    ThisList.RemoveAt(Ndx)
  Else 
    Element.Enjoy 
  end if
next
 
Upvote 0
Top