Iterating a list, and deleting from it, Java vs .NET

Or how I came to realize I could live a life time without .NET and be just as happy.

I'm just fresh from having tried to iterate a list... and delete items from it while iterating.  In .NET with C#.

It turns out a statement like:

void deleteFromList(IList<X> list) {
     foreach (X x in list) {
        if (x.DeleteMe) {
            list.Remove(x);
        }
    }
}

Will throw an InvalidOperationException stating you cannot perform a foreach and delete at the same time.  This is actually not that big of a surprise, or it shouldn't be...  the same happens in Java if you delete and iterate at the same time.

This is how I would have done this in Java:

void deleteFromList(List<X> list) {
     Iterator<X> itr = list.iterator();
     while (itr.hasNext()) {
	X x = itr.next();
        if (x.DeleteMe) {
            itr.remove();
        }
    }
}

It's simple, clean and it does not throw exceptions. If you believe the code may be run asynchronously, slap on a "synchronized" and you're home safe.

So, how to do this with .NET?  Well, you can't use Enumerators (which are the .NET "equivalent" of iterators), they don't have a remove method.  Further worse, if you are unlucky enough to run version 1.1 your only option seems to be some unholy concoction like:

void deleteFromList(IList<X> list) {
    IList<X> toBeDeleted = new List<X>();

    foreach (X x in list) {
        if (x.DeleteMe) {
            toBeDeleted.Add(x);
        }
    }

    foreach (X x in toBeDeleted) {
        list.Remove(x);
    }
}

Don't even start a conversation on synchronization with this mixup.  Anyway, those who are "lucky" enough to code .NET 2.0 can do something like:

myList.RemoveAll(delegate(X x) { return x.DeleteMe; });

Now, if you'd like to base the "DeleteMe" calculation on some external paramter like input to the deleteFromList method or if you'd like to do more than just delete x you'll have to experiment, it's probably possible... with a solution like the double lists above perhaps?

Regardless.  Someone said it was old news to be a Java programmer, I can only guess because of the lower hour wastage when you program Java systems, which in turn means lower bills to the clients and finally lower wages to the programmers.

It costs to be on top...