Feb 16, 2008
簡単なHashの作り方。
RubyのHashを作るのは早くて簡単。
name = {"title", "mr", "first", "craig", "last", "davidson"}
Javaでは通常以下のようになる。
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"));
}
それを以下のようにしてみたい。
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"));
}
それは以下のようにHashを拡張すればいい。
public class Hash extends HashMap {
public Hash(Object ... keyValuePairs) {
for (int i=0; i<keyValuePairs.length; i++)
put(keyValuePairs[i], keyValuePairs[++i]);
}
}
Edit this entry...
wikieditish message: Ready to edit this entry.
A quick preview will be rendered here when you click "Preview" button.