simple Java Set/Map initialization
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"); }};
}
See also:
File Upload in Servlet 3.0
OutOfIdeasException
Deploying Processing apps using WebStart
Handassembled java bytecode