ArrayCollection contains() uses your sort!

Here’s another gotcha that took me a while to realize what was wrong.

I was using an ArrayCollection to hold a collection of items. I had a custom sort applied since the items were typed objects that needed to be sorted according to certain, out-of-the-ordinary fields. In the sort method, I was comparing values and returning either -1 or 1.

return itemA > itemB ? -1 : 1;

From the docs for a compareFunction:

The method used to compare items when sorting. If you specify this property, Flex ignores any compareFunction properties that you specify in the ISortField objects that you use in this class.

The compare function must have the following signature:

         function [name](a:Object, b:Object, fields:Array = null):int

This function must return the following value:

  • -1, if the Object a should appear before the Object b in the sorted sequence
  • 0, if the Object a equals the Object b
  • 1, if the Object a should appear after the Object b in the sorted sequence

To return to the internal comparision function, set this value to null.

I decided that instead of returning 0 if they were the same, I would just let it stick it below the item. No big deal.

Later, when checking to see if an item was selected, I used the contains() method to see if an item was in the ArrayCollection. I quickly noticed that it wasn’t finding my item, even when I knew it was in the list.  Stepping through the code, and diving in to the Flex framework classes, I found that the contains() method uses the custom sort compare method to compare the item you’re looking for with the items in the list. It determines it found the item when it gets 0 back from the compare function. Since my custom compare method never returned 0, it never found the item.

Knowing this also helped me optimize the compare method for finding items.  Instead of thinking just in terms of whether one item goes before or after another item (or at the same level), I could also think about the comparisons in terms of checking to see if itemA was itemB.



Tags: , , ,
This entry was posted on Tuesday, May 24th, 2011 at 11:21 pm and is filed under Flex4. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “ArrayCollection contains() uses your sort!”

  1. Rob Sheely

    Wow, that is one giant gotcha. Thanks for this post. I’m sure it will save my ass sometime in the future!

Leave a Reply

Your comment