Section 11.9. Maps

   

11.9 Map s

The Map replaces the Dictionary class. Dictionary used to be the superclass of any implementation that paired keys with values in the manner of a ColdFusion structure. There are many different kinds of maps, but only two that are used with much frequency. The most popular maps are HashMap and TreeMap , which we will look at here.

The following things are true of Map s.

  • Map s store key-value pairs called entries.

  • Each key must be unique within a Map , and any entry may point to only one value.

  • The key and the value can be of any object type. That is, you cannot store primitive types.

  • The Map interface offers three collection views: as a set of keys ( keySet() ), as a collection of values ( values() ), or as a set of key-value mappings ( entrySet() ).

  • It is a good idea to override equals() so that only the value is compared, not the object reference.

Map s are very flexible, and as such, are used frequently. Map s do not implement the Collection interface. If you want to use the methods it provides, you can locally convert your Map to a Set with Map.entrySet() .

11.9.1 Comparator

Some Collections, such as the TreeMap and TreeSet , implement the Comparator interface. A comparator is a function that compares two objects, returning a negative value if a comes before b , or zero if they are considered equivalent in the sort order, or a positive value if a comes after b . The comparator takes two arguments: the objects to be compared.

11.9.2 HashMap

Here are things that are the case about HashMap :

  • HashMap stores its keys in an unsorted fashion.

  • Because its data is unsorted, operations perform very quickly.

  • HashMap replaces Hashtable . Hashtable is a legacy class that should no longer be used, though you are likely to see it in legacy code.

  • Permits null values and null keys.

  • It is unsynchronized.

  • The class does not guarantee any order of data, or that the data order will stay consistent over time.

One nice thing about a HashMap is that it features a loadFactor , which you can specify in its constructor. The loadFactor , as in an SQL Server database, allows you to specify how full the capacity should become before the HashMap should automatically grow in size . It is a better idea in terms of performance to create an initial capacity that you think will be big enough for your HashMap .

Note

There is a special kind of HashMap called a WeakHashMap , which is nearly identical to the HashMap class. The only real difference is that WeakHashMap calls the garbage collector to remove a key that is no longer in use. Therefore, the only common use for WeakHashMap is for caches of data, which need not persist reliably.


HashMap s use the put() and get() methods familiar from FTP to insert and retrieve data. Here is an example to demonstrate the use of HashMap s:

11.9.3 HashMapTest.java

 /*   * HashMapTest.java  *  */ package chp11; import java.util.*; public class HashMapTest {     public static void main (String [] a) {             // constructor uses Float for loadFactor         HashMap map = new HashMap(5, 4.0F);             // is map empty?         System.out.println("Is map empty? " + map.isEmpty());             // print map size         System.out.println("map size: " +  map.size());             // add an item in the form 'key','value'             // this is equivalent to             // StructInsert() in CF         map.put("width","50");         map.put("height", "25");         map.put("robots", "all");         map.put("revist-after","30 days");             // now delete the 'robots' key         map.remove("robots");             // ternary operator like IIF() in CF         String s=map.containsKey("width") ? "true" : "false";             // print answer         System.out.println("Is width a key? " + s);         System.out.println("Its value is: " + map.get("width"));         String x = map.containsValue("30 days") ? "yes" : "no";         System.out.println("map contains 30 days? " + x);     } } 

11.9.4 TreeMap

Here are things that are the case about TreeMap :

  • TreeMap stores its keys in a sorted fashion. This contrasts with HashMap .

  • Because data is sorted, all operations are slower than with HashMap .

  • Keys stored in a TreeMap must implement the Comparable interface.

There are several methods useful in working with TreeMap s, as shown below:

  • firstKey() returns the first key; that is, the key with the lowest value.

  • lastKey() returns the last key (the one with the highest value).

  • containsKey(Object key) returns true if the collection contains the key specified.

  • containsValue(Object value) returns true if the collection contains the value specified.

  • size() returns the number of keys in the map.

  • comparator() returns the comparator used to order this map.

The following class covers new items regarding HashMap s and TreeMap s and demonstrates a useful implementation of an anonymous inner class.

11.9.5 TreeMapTest.java

 /*   * TreeMapTest.java  * demonstrates Comparator use, and  * anonymous class use, as well as  * transferring data from a HashMap into a TreeMap  */ package chp11; import java.util.*; public class TreeMapTest {     private String value;  public static void main(String[] ar) {         // create new Map to store key-values      HashMap characters = new HashMap();         // add characters from Faulkner novel         // out of order      characters.put(new TreeMapTest("Vardaman"), "fish");      characters.put(new TreeMapTest("Anse"), "dad");      characters.put(new TreeMapTest("Addie"), "dead");         // anonymous inner class Comparator         // to put characters into new         // tree map sorted      TreeMap tm = new TreeMap(new Comparator() {         public int compare(Object a, Object b) {             return ((TreeMapTest)a).value.                    compareTo(((TreeMapTest)b).value);             }});             tm.putAll(characters);             System.out.println("sorted characters: " + tm);  }         // constructor     TreeMapTest(String value) {         this.value = value;     }         // override toString     public String toString() {         return "\n" +  value;     } } 

The output produced by this example is as follows :

 sorted characters: { Addie=dead, Anse=dad, Vardaman=fish} 

   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net