public class Main {
private static Map<String, Integer> myMap = new HashMap<String, Integer>();
static { // Static things load from top to bottom so putting the map below this code block results in an illegal forward reference
myMap.put("1", 1);
myMap.put("2", 2);
myMap.put("3", 3);
myMap.put("4", 4);
}
public static void main(String[] args) {
for (Entry<String, Integer> entry : myMap.entrySet()) {
System.out.println(entry.getKey()+ ": " + entry.getValue());
}
}
}
The static block gets called in the order its placed. With this if you're working with static things you can put initialization code into a static initializer instead of having a method that needs to be called before things are used inside of the class.
4 replies to this topic
#1
Posted 27 December 2010 - 11:13 AM
|
|
|
#2
Posted 21 February 2011 - 06:59 AM
Thank you, that was really useful. I believe I will a good use to it.
#3
Posted 21 February 2011 - 11:19 AM
I didn't even knew that.
The time that I have a need for such a static block has yet to come but thanks for sharing :)
The time that I have a need for such a static block has yet to come but thanks for sharing :)
#4
Posted 21 February 2011 - 11:47 AM
^
I've been programming for a while now, and I had the need for a static block, but whenever I needed to use it, I just put the code instead the first lines of each constructor. Kinda silly and code reuse, but it worked properly. :D
I've been programming for a while now, and I had the need for a static block, but whenever I needed to use it, I just put the code instead the first lines of each constructor. Kinda silly and code reuse, but it worked properly. :D
#5
Posted 21 February 2011 - 02:30 PM
I've found the static block to be good for complex initializations of class-wide static-finals. Also, if you get into loading classes dynamically, they can be really useful for some particularly interesting tricks. :) For example, the JDBC API requires that each implementor of a JDBC frontend must register their driver to the JDBC DriverManager. This must be done when the frontend class is loaded into the JRE (IE, using a static block, you must register the driver using DriverManager.registerDriver()).
Wow I changed my sig!
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









