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"); }};
}
Tweet This! submit to reddit Digg! Tags: | no comments | no trackbacks

See also:

SFZ to Multisample converter
File Upload in Servlet 3.0
OutOfIdeasException
Deploying Processing apps using WebStart
Handassembled java bytecode

Trackbacks

Comments

Leave a response

Leave a comment