static int class_variable = 0;
This way, all the instances of the class share this variable (this also means you have to be careful about concurrency control). Now, what if you want to do this with a Collection, instead of a primitive type?
That's where static blocks come in handy. Imagine we have this:
static HashMap<Integer,String> sharedHash = new HashMap<Integer,String>();
What we want now is to populate the HashMap, either from hardcoded values or a function that does the job. The solution is simple, a static block!
static { sharedHash.put(1,"one"); this.populateHash(sharedHash); }
This populates the HashMap only once, and only when the first instance of the class is created, saving a lot of unnecessary processing and memory usage.
No comments:
Post a Comment