simple Java Set/Map initialization

Nikolaus Gradwohl2008-04-20T07:55:00+00:00

When you need a array in java filled with some data, initializing it is easy

String[] bla = new String[] { "Foo", "Bar", "Bla" };

and done. but when you need a Map or a Set prefilled with some data it starts getting complicated. you can either use a static initializer block like

public class Bla {
    static Set<String> dings;
    static {
        dings = new HashSet<String>();
        dings.add("foo");
        dings.add("bla");
    }
}

or you fill your set or map in the contructor if it is still null (be carefull if you use this in a multithreaded application)

another way i have learnd at the last jax is using this code

public class Bla {
    static Set<String> dings = new HashSet<String>() {{ 
        add("Foo"); add("Bar"); add("Bla"); }};
}

neat isn't it?

this also works with a Map

public class Bla {
    static Map<String,String> dings = new HashMap<String,String>() {{ 
        put("k1", "Foo"); put("k2", "Bar"); put("k2", "Bla"); }};
}
read more ...

Typo Update

Nikolaus Gradwohl2008-04-10T07:32:00+00:00

I recently updated my blog to the latest shiny blinking bleeding edge "typo version":http://www.typosphere.org the updates really went very smooth and my nagios tells me that the stability has improved very much :-)

read more ...