AS3 HashMap for Flex 2

The inclusion of the Dictionary class in ActionScript 3 creates numerous possibilities when sub classing. The Dictionary class allows for creating key / value mappings or tables which are more commonly known as Hashes or Hash Maps. The only problem is that the Dictionary class does not provide an API for working with the map. The Dictionary class is a good starting point in which sub classes can create managed key / value hash maps and provide methods for retrieving values and keys as well as removing values, determining how many key / values exist and so on.

I am working on a project in which the data set is comprised of sentences tokenized into their individual parts of speech; noun, verb, preposition etc. Part of the requirement is that a lookup can be made on any individual part of speech to retrieve further information such as tense, plurality and so on. At first I simply used a Dictionary for the mappings but ended up adding all kinds of logic outside of the map whenever I needed to check for a key or add a value and so on. So I decided to write a simple HashMap class for AS3 which is similar to the HashMap available in java.util.HashMap.

Below is an example of how to use the HashMap class:

import com.ericfeminella.collections.IMap;
import com.ericfeminella.collections.HashMap;

var map:HashMap = new HashMap();
var o:Object = {name: "HashMap Example"};
map.put(‘name’, o);

trace(map.containsKey(‘name’)); //true
trace(map.containsValue(o)); //true
trace(map.size()); //1
trace(map.getValue(‘name’)); //[Object object]
trace(map.isEmpty()); //false

map.clear();

trace(map.containsKey(‘name’)); //false
trace(map.containsValue(o)); //false
trace(map.size()); //0
trace(map.getValue(‘name’)); //false
trace(map.isEmpty()); //true

You can view the source for the HashMap class as well as the IMap interface which defines the methods necessary for working with the HashMap.

20 Responses to “AS3 HashMap for Flex 2”

  1. Actionscript Classes » HashMap UNITED STATES Says:

    […] http://www.ericfeminella.com/blog/2006/12/05/as3-hashmap-for-flex/ […]

  2. lievencardoen BELGIUM Says:

    Thx. Really usefull. Strange that this isn’t in Flex SDK. Lieven Cardoen, IndieGroup, Belguim

  3. levani UNITED STATES Says:

    I have smal issue with hashp map,
    if I do myHashMap.remove(”abc”);

    it removes the value but leaves the key its not even nulling it, it is extremly strange because when I do:
    Alert(myHashMap.size()); // returns 2)
    myHashMap.remove(”abc”);/
    Alert(myHashMap.size()); // returns 1) so it sounds like it removes it

    but in :

    for each ( var myObj:MyValueObject in myHashMap){
    myObj.mymethod // throws Null Pointer Exception

    }

    after I debug I see following inside myHashMap

    it has two keys but one of the keys value is null.what am I doing wrong?

  4. eric UNITED STATES Says:

    Strange, make sure that you are using the latest version:
    http://code.ericfeminella.com/classes/as3/HashMap.as.html

    There was an issue in the original version whereas the values were being set to null rather than deleted. I have since updated the HashMap API to delete items completely, thus removing them from the instance. Give the updated version a try and let me know if this fixes the issue.

    Thanks,
    Eric

  5. levani UNITED STATES Says:

    I got the utils.swc from here,about 3 weeks ago probably it was wrong version. anyways I just grabbed source now and build it from source to make sure , I will test delete, (I had to modify code to not use remove so I will go back and try with remove again)

    I have also added one api Method - I needed “putAll” (not sure if its any use but will paste it here anyways )

    /**
    *
    * Adds (appends) a hashMap contend to *this* existing HashMap
    * if Null or HashMap size of 0 is passed it does nothing
    * NOTE: Order of Apended HashMap content is not predictable.
    *
    * @param the HashMap to add to this HashMap
    * @param the forceUpdate Boolean to force it to override
    * value in *This* Object,if key for that value, matches with key of parameter HashMap.
    * @return Number of Items added to the HashMap
    */
    public function putAll(_newMap:IMap, _forceUpdate:Boolean=false) : int {
    var _counter:int=0;
    if(_newMap!==null && _newMap.size()>0){
    for (var prop:String in _newMap) {
    if (!this.containsKey(prop) || _forceUpdate){
    this[prop] = _newMap[prop];
    _counter++;
    }
    }
    }

    return _counter;
    }

  6. levani UNITED STATES Says:

    something wrong, There is a strange bug somewhere, I have a case that I add two items to hashtable following way

    this.defaultRoleRegistry = new HashMap();
    this.defaultRoleRegistry.put(”public”, new Role(”public”,-1));
    this.defaultRoleRegistry.put(”system”, new Role(”system”,-999));

    then I run right after that :

    Alert.show(defaultRoleRegistry.size()+”

  7. levani UNITED STATES Says:

    further investigations
    while for each does not work(strange it used to work before).
    but if I loop this way (it works)
    Alert.show(defaultRoleRegistry.size()+”

  8. eric UNITED STATES Says:

    As I had mentioned in a previous post I have refactored the HashMap API from an “is-a” relationship to a “has-a” relationship in order to provide security to the map from unintentional misuse.

    Therefore you can only access the underlying map (Dictionary) in a HashMap instance via the operations defined in the IMap interface, which is implemented by the HashMap.

    For more details please see:
    http://www.ericfeminella.com/blog/2007/09/11/as3-hashmap-update/

    Thanks,
    Eric

  9. levani UNITED STATES Says:

    NOTE:: changing API from IS a to Has a introduced small inconvenience, problem is that now hashmap is impossible to debug, because it has no public properties, and debugger cant read methods, I would say changing getKeys api method (in IMAP) to function get keys and getValues method to function get values will take care of the problem, otherwise cant debug hashmap.

  10. eric CANADA Says:

    This is not true, any object and all of it’s members can be debugged in Flex, otherwise it woulf kind of defeat the purpose of debugging.

    What you need to do is enable “Show inaccessible Member Variables” in the Flex Debugging perspective in order to see them.
    To do so simple go into the Flex Builder Debug perspective, in the top right hand corner select the arrow icon (the 3rd from last icon) select Flex and then check “Show inaccessible Member Variables”.

    That’s it. Now debug as needed.

  11. levani UNITED STATES Says:

    nice tip,it does show internal map variable now, I never thought that option would be buried there, I guess thats also default in java debugger,

  12. Mario GERMANY Says:

    Additional explanation: The code above is basically the same HashMap, but it is bindable. You will need it i.e. if you want bind GUI components to the HashMap.

  13. Tim UNITED STATES Says:

    Nice post. I was about to implement my own HashMap from the Dictionary until i found this. Thanks for saving me some work!

  14. Ziad FRANCE Says:

    Good Morning,

    Thank you very much for those classes, they are very helpful.

    What I want know is how I can iterate on the map?

    Thank you again.

  15. Ziad FRANCE Says:

    Hello,

    Now it’s fine, I iterate on my Map,

  16. Michael Jenik ARGENTINA Says:

    Thanks.. As Tim said : ” I was about to implement my own HashMap from the Dictionary until i found this. Thanks for saving me some work!”

  17. sanjeev INDIA Says:

    is it woks with flex3 as I am getting some error for ‘IHashMapEntry’

  18. Kai Mai UNITED STATES Says:

    You also need to get the following files:
    http://code.ericfeminella.com/classes/as3/HashMapEntry.as.html
    http://code.ericfeminella.com/classes/as3/IHashMapEntry.as.html

  19. e9 UNITED STATES Says:

    I’m using Flasch cs4 (still haven’t switched to Flex or flashdevelop). anyway, I downloaded and began implementing your collections package…It turns out that Flash (at least for me) does not have the mx.collections.IList class that you import in the IMap interface… i decided to see what would happen if i just commented out the import (terrible i know..but i really didn’t want to reinvent the hashmap wheel )… from some experiments so far, I seem to be able to use the classes without mx.collections.IList — i have been able to set, get, nadremove keys and values without any problems yet.

  20. eric UNITED STATES Says:

    If you go to the http://www.ericfeminella.com/blog/actionscript-3-apis/ page you can always find the latest versions of all OS APIs I have published. The latest versions of the HashMap API do not contain any references to Flex framework components.

Leave a Reply