Adept Open Source Library

This is a blog to provide in-depth information on the Adept open source library - the core of which is a Java object database component. In addition there is lots of Java code and solutions for many development problems.

http://marringtons.com

Wednesday, April 13, 2005

Map Initialisation

Java provides a dictionary-like facility called a Map of which the most popular version is HashMap. They are great for keeping name/value pairs and are used heavily in almost all programs where type-safe naming is too restrictive. Most interpretive languages such as Perl or Python provide methods to initialise a dictionary in code, but native Java has no such built-in tool.

No fear, it's easy to build - and the Adept library has a Map helper class in the util package with two static load() methods. One to create a HashMap and another where the map is provided so that you can use another variant such as a LinkedHashMap. Both methods use arrays to provide the information to load the map.

Examples

Map fieldTranslation = Maps.load( new Object[]
  {
    "integer", "integer",
    "aLong", "anotherLong",
  });

Map pronounce = Maps.load( new LinkedHashMap(),
  new Object[]
    {
      "a", "aye",
      "b", "bee",
      "c", "see",
      "d", "dee",
      ...
    });

 

Sets

Sometimes maps are used as sets - being a collection of keys without values. The library class com.marringtons.util.Maps has two methods for working with map sets.
FileReader fileReader = new FileReader();
fileReader.setArchive(
    "com/marringtons/util/system.resourceTest.zip");
String[] files = fileReader.listArchive();

Map map = Maps.loadSet( files);
assertTrue( map.containsKey(
    "level1/level2/test in zip.txt"));
assertTrue( map.containsKey(
    "META-INF/PATH-BASE.TXT"));
assertTrue( map.containsKey(
    "META-INF/PROPERTIES.TXT"));
assertTrue( map.containsKey(
    "level1/system.properties.txt"));

String[] files = fileReader.listArchive();
Arrays.sort( files);
Map map = Maps.loadSet( new LinkedHashMap(), files);

 

0 Comments:

Post a Comment

<< Home