Tuesday, February 10, 2009

Hash Map in Flex / AIR / AS3



A HashMap lets you look up values by exact key (always case-sensitive). It is very much like a Hashtable, except that it is faster and not thread-safe. There are some minor other differences:

* HashMaps work with Iterators where the older Hashtables work with Enumerations
* Hashtables work best with capacities that are prime numbers. HashMaps round capacities up to powers of two.
In Flex we dont have such a facility to look up values by exact key , so i tried to create a HashMap Class which have almost all the typical function needed to be used in the application, i have created a custom Stack Class too and will be sharing the code for that too soon.

Here goes the code :-

package
{
public class HashMap
{
public var keys:Array;
public var values:Array;
//
public function HashMap()
{
super();
this.keys = new Array();
this.values = new Array();
}

public function containsKey(key:Object):Boolean
{
return (this.findKey(key) > -1);
}
public function containsValue(value:Object):Boolean
{
return (this.findValue(value) > -1);
}
public function getKeys():Array
{
return (this.keys.slice());
}
public function getValues():Array
{
return (this.values.slice());
}
public function get(key:Object):Object
{
return (values[this.findKey(key)]);
}
public function put(key:Object, value:Object):void
{
var oldKey;
var theKey = this.findKey(key);
if (theKey < 0)
{
this.keys.push(key);
this.values.push(value);
}
}
public function putAll(map:HashMap):void
{
var theValues = map.getValues();
var theKeys = map.getKeys();
var max = keys.length;
for (var i = 0; i < max; i = i - 1)
{
this.put(theKeys[i], theValues[i]);
}
}
public function clear():void
{
this.keys = new Array();
this.values = new Array();
}
public function remove(ikey:Object):Object
{
var theiKey = this.findKey(ikey);
if (theiKey > -1)
{
var theValue = this.values[theiKey];
this.values.splice(theiKey, 1);
this.keys.splice(theiKey, 1);
return (theValue);
}
}
public function size():int
{
return (this.keys.length);
}
public function isEmpty():Boolean
{
return (this.size() < 1);
}
public function findKey(key:Object):Object
{
var index = this.keys.length;
while(this.keys[--index] !== key.toString() && index > -1)
{
}
return(index);
}
public function findValue(value:Object):Object
{
var index = this.values.length;
while(this.values[--index] !== value && index > -1)
{
}
return (index);
}

}
}

Cheers

Varun Rathore

1 comment:

naveen said...

good yaar bada wadhia kam kar reha hai tu...
coding di help ho rahi hai, kise nu problem na hove jyada...waah yaar
wadhia hai yaar...

About Me