Can anyone please explain me in which scenario we use static initial block?
5 Answers
You can use it as a "constructor" for static data in your class. For example, a common situation might be setting up a list of special words:
private static final Set<String> special = new HashSet<String>();
static {
special.add("Java");
special.add("C++");
...
}
These can then be used later to check if a string matches something interesting.
Comments
I use them all the time to initialize lists and maps.
List<String> myList = new ArrayList<String>(){{
add("blah");
add("blah2");
}};
for(String s : myList){
System.out.println(s);
}
5 Comments
Scott Stanchfield
He was asking about static initializers. That's an example of an instance (non-static) initializer.
Scott Stanchfield
(It is a good example of an instance initializer though, which is useful for setup in anonymous inner classes as you demonstrated)
Scott Stanchfield
Just be aware that that actually creates a subclass of ArrayList!
Matt Klooster
I know. It's not the most memory efficient thing either from what I've heard.
Mark P.
This is definitely frowned upon, creating the subclass of ArrayList. Generally, the more preferred approach for this would be: List<String> myList = Arrays.asList("blah", "blah2"); Only problem here is that you can't control the type of the List, if that is important to you.