Map Class

Map Class

Map (Foundation class) consist of a data set that contains a key and a corresponding value, where the key is unique. The key and the value need not be from the same data type.

A Map is always sorted on the key value.

Contents

 [hide]

[edit]How to use

[edit]Define

Map m = new Map(Types::STRING, Types::INTEGER);

or

Map m = new Map(typeId2Type(typeid(recId)), Types::Record);

[edit]Insert a value

m.insert("Wassini", 37);
m.insert("Eric", 102);

[edit]Exists value

To see if a value already is added, use the exists method:

if (m.exists("Wassini"))
   print "Yes!";
else
   print "No!";

[edit]Lookup value

To get the value linked to a specific key use the lookup method:

Integer i;   i = m.lookup("Wassini"))

If key don't exist in map lookup function throw error so is better to test before is key exist

[edit]Getting values

There are several ways to get the values in the map.

  1. Using a MapIterator
  2. Using a MapEnumerator
  3. Using a direct method

[edit]MapIterator

The MapIterator loops throug the complete map:

MapIterator mi;   mi = new MapIterator(m);   while (mi.more())
{
  print mi.key();
  print mi.value();   mi.next();
}

[edit]MapEnumerator

MapEnumerator Class is like MapIterator Class, but does not allow the deletion of elements during enumeration. MapEnumerator Class automatically created on the same tier as the Map Class, and MapIterator does not.

MapEnumerator me = m.getEnumerator();   while (me.moveNext())
{
  print me.currentKey();
  print me.currentValue();
}

[edit]Direct method

It is possible to get find a specific value from the key:

print m.lookup("Wassini");

[edit]Removing values

Just use the remove method to remove the active key/value pair.

m.remove("Wassini");

[edit]Updating values

It is not possible to update a value directly:

int age;
str keyid = "Wassini";   age = m.exists(keyid) ? m.lookup(keyid) : 0;
m.insert(keyid, age + 1);

[edit]Other methods

// Get number of elements:
print m.elements();   // Get the used types:
print m.definitionString();   // Dump the whole map as a string:
print m.toString();

[edit]Passing across tiers

As with other foundation classes, the Map can be passed across tiers by converting it to a container. The pack method converts it to a container:

container packedMap = m.pack();

To convert the packed container back to a Map, call the static create method of the Map class:

Map map = Map::create(packedMap);

[edit]See also

posted @ 2012-02-15 17:40  perock  阅读(934)  评论(0编辑  收藏  举报