15 Feb 2008

Friendlier Java Hashes in only 2 lines of code!

Creating hashes in Ruby is fast and simple:


name = {"title", "mr", "first", "craig", "last", "davidson"}

Why does it need to be such hard work in Java? The standard way of creating a hash in Java is something like:

public void testBuildAHashNormally(){

     Map slow = new HashMap();
     slow.put("title", "mr");
     slow.put("first", "craig");
     slow.put("last", "davidson");

     assertEquals("mr", slow.get("title"));
     assertEquals("craig", slow.get("first"));
     assertEquals("davidson", slow.get("last"));
}


Lets do it like this...

public void testBuildAHashQuickly(){

     Map quick = new Hash("title", "mr",
                "first", "craig", "last", "davidson");

     assertEquals("mr", slow.get("title"));
     assertEquals("craig", slow.get("first"));
     assertEquals("davidson", slow.get("last"));
}


Much easier! To make the test pass is simple...

public class Hash extends HashMap {
   public Hash(Object ... keyValuePairs) {
     for (int i=0; i<keyValuePairs.length; i++)
       put(keyValuePairs[i], keyValuePairs[++i]);

   }
}

Our Hash can do everything a HashMap can do.
That's our friendlier Java hash in 2 lines of code!