public class Foo {
private static final Map<String, Object> CACHE;
static {
CACHE = new HashMap<String,Object>();
CACHE.put("foo", new Object());
CACHE.put("bar", new Object());
}
}But I saw this the other daypublic class Foo {
private final List<String> emailAddresses;
{
emailAddresses = new ArrayList<String>();
emailAddresses.add("foo@bar.com");
}
}Did some research and looks like an instance initializer, which is just like a static initializer except is run every time an instance of the class is created.
Very useful if there are multiple constructors for a class, and you don't want to keep running the same initialization code over and over again.
Some interesting examples here

No comments:
Post a Comment