views:

670

answers:

2

Flash implements a dictionary (that is, something like a HashMap) using two approaches. One approach is the flash.utils.Dictionary class, and the other is a generic Object. I'd like to check how many key:value pairs are in the dictionary. In most cases I'd simply like to know it there are any key:value pairs, that is, just check if it's empty.

The documentation hasn't been much help on this point. Is there a simple and clear way to do this? Failing that, is there an ugly, yet not too brittle way to do this?

+3  A: 

The only way that comes to mind is to iterate through all the keys and count them - like so:

var count:int = 0;

for (var key:Object in dict)
{
   count++;
}

Pretty lame - but I think that is what you are left with. Note that the Dictionary is just a really really really thin wrapper for the vanilla Object.

Shane C. Mason
+5  A: 

This will reliably tell you if a particular dictionary is empty:

function isEmptyDictionary(dict:Dictionary):Boolean
{
    for each(var obj:Object in dict)
    {
        if(obj != null)
        {
           return false
        }
    }
    return true;
 }

Note that you need to do the obj != null check - even if you set myDictionary[key] = null, it will still iterate as a null object, so a regular for...in loop won't work in that instance. (If you are always using delete myDictionary[key] you should be fine though).

Reuben
This seems like a solution for bad practices. Removing an entry from the dictionary should remove both the key and the value. If for some reason, I want to remove the value but leave the key, then the dict isn't really empty -- it has some (apparently meaningful) keys in it.
Dan Homerick
Fair enough. If you remove the (obj != null) statement then this will work, but I'm guessing the other answer will work too...
Reuben