I know that Initialization blocks run when the class is first loaded (a static initialization block) or when an instance is created (an instance initialization block).
class SmallInit {
static int x;
int y;
static { x = 7 ; } // static init block
{ y = 8; } // instance init block
}
But what is the special benefit of this, when we can do it like this:
class SmallInit {
static int x = 7;
int y = 8;
}
One nice thing about instance initialization blocks is that they make the Double Brace Initialization pattern possible.
Instead of this:
Set<String> names = new HashSet<String>();
names.add("Peter");
names.add("Paul");
names.add("Mary");
You can do this:
Set<String> names = new HashSet<String>() {{
add("Peter");
add("Paul");
add("Mary");
}};
The first brace creates an anonymous inner class; the second starts the instance initializer block. (Note that this means names is an instance of an anonymous subclass of HashSet, but that's often not an issue. This also means that this pattern only works for non-final classes.)
This is especially useful in one-off situations where it would be convenient to initialize an object as an expression. For example:
doSomethingToSet(new HashSet<String>() {{
add("Peter");
add("Paul");
add("Mary");
}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With