Removing items from an Array Collection

Author: Thomas Gonzalez

Today I was troubleshooting a bug where items weren't not being removed from a Flex DataGrid the way I expected them to. What I discovered is that in this particular case my laziness in abusing the ArrayCollection was causing an unobvious (to me) bug.

Here is the simplified code that looks for a match to remove items from an ArrayCollection (yes I could use a filter, but that doesn't TRULY remove items from the ArrayCollection.source, and I can never remember the 5 lines of code I need to create one correctly.) So this was my first attempt at removing items from an ArrayCollection.

  
ac.addItem("foo1");
ac.addItem("foo2");
ac.addItem("foo3");

for each (var foo:String in ac) {
if (foo.charAt(0)=="f")
ac.removeItemAt(ac.getItemIndex(foo));
}


Now, what would you expect that trace statement to output? Personally I expected to see a big "0", but alas the ArrayCollection is not truly keeping proper indexes as iterates through its for each. Realizing that this was probably an index issue with the iterator I wrote the following which works correctly as it backs down from the last element, thus not distrupting the index as it moves backwards.

for (var i:int=ac.length-1; i>=0; i--)
{
if (ac.source[i].charAt(0)=="f")
ac.removeItemAt(i);
}

The above code does what I was intending, correctly. I guess a lesson learned on thinking that Flex did EVERYTHING for me... guess I can't be a completely lazy programmer.

 

4 Responses to “Removing items from an Array Collection”

  1. levani

    Hi Tom,
    this is a notariouse issue, thats one of the reaons java uses Iterators for collections, that reson that "bug" occures is because you are iterating over ac :
    for each (var foo:String in ac)
    and inside it you are removing item from same ac, to be short, either you have to write iterator or make copy of that collection and then iterate through that and remove from original


  2. Thomas Gonzalez

    Hi Levani,

    Yes, I realize this "bug" is not a true bug. Really something more born of my laziness, but since the ArrayCollection actually wraps an Array and provides filtered views I wrongly assumed it was "smart" enough to handle a dynamic index within a loop. Thanks for your comments, keep them coming.

    - Tom


  3. Anonymous

    Nice one! Iterating backwards seems rather obvious now that I've seen your post - but I bet I would have written something far mor complicated unless I happened to read this.
    -Thanks a lot for posting! :-)


  4. Thomas Gonzalez

    Hi Culme,

    Glad it saved you some time... these are classic reference pointer issues, that I think we all mistakenly assume get hidden from us in 4/5GL languages like Flex, I guess not!

    - Tom


Leave a Reply