1 Reply Latest reply on Oct 14, 2009 8:44 AM by msakrejda

    Using my objects as keys in a hash map

    sam_bercovici

      I need the following type of code to work (ClDate is my own class):

       

                  var testDic:Dictionary = new Dictionary();
                  var key1:ClDate = new ClDate(10000);
                  var key2:ClDate = new ClDate(20000);
                  var key3:ClDate = new ClDate(30000);
                  var key4:ClDate = new ClDate(40000);
                  testDic[key1] = 1;
                  testDic[key2] = 2;
                  testDic[key3] = 3;
                  testDic[key4] = 4;
                 
                  var key:ClDate = new ClDate(20000);
                 
                  var retNum:Number = testDic[key];

       

      The current Dictionary or Array does not work since they do not enable passing a comparison function that will enable comparing my own objects. Is there any existing implementation that works?

       

      -Sam.

        • 1. Re: Using my objects as keys in a hash map
          msakrejda Level 4

          Object (when acting as a map) uses toString() as a poor man's hashcode implementation, so you can get more-or-less the behavior you want by implementing the toString() method in your CIDate class and then storing the instances in an Object (rather than a Dictionary).

           

          E.g., say your CIDate looks like this:

           

                    public class CIDate {

                      public var num:Number

                      public function CIDate(num:Number) { this.num = num }

                      public function toString():String { return num.toString(); }

                    }

           

          You can use toString() as a comparison operator by keeping things in an Object instead of a Dictionary:

           

                      var testDic:Object = {};
                      var key1:ClDate = new ClDate(10000);
                      var key2:ClDate = new ClDate(20000);
                      var key3:ClDate = new ClDate(30000);
                      var key4:ClDate = new ClDate(40000);
                      testDic[key1] = 1;
                      testDic[key2] = 2;
                      testDic[key3] = 3;
                      testDic[key4] = 4;
                     
                      var key:ClDate = new ClDate(20000);
                     
                      var retNum:Number = testDic[key];

           

          Then retNum should be '2', as expected. This is sort of a hack, but it might work for what you're doing.