This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi, I want to have a HashMap that holds a few key value pairs for the application. The HashMap should be availible as long as the application is alive. I should be able to add/remove objects from the HashMap.
Can I achieve the above requirements if I make the HashMap instance static and do initialization in a static initializer block?
In short yes as long as you are instanciating only one JVM. However do you really need to do this, this is not always the best design choice? If the answer is yes then check out the Singleton Pattern note however this is one of the most overused and misunderstood patterns of them all here is a link
Yes, that would work. However, I would like to point out that there are other options depending on other things. Here are a few things you might want to consider: What is the purpose of this HashMap? When does this it need to be created (i.e. what is the earliest method in the program that needs to access it)? What class should be in charge of creating it (whether it's a static or non-static member)? What other classes need access to the HashMap?
There may be other considerations to think about, too, but these are the ones that come to mind. Depending on your answers to these questions, one option is to create it in main() or the constructor of one of your major classes then pass it as a parameter to other constructors or methods. I'm sure there are other alternatives, but everything I can think of are basically variations on this theme.
Anyway, I hope this gives you some ideas to think about. Personally, I don't like to lock myself into one particular option without considering other alternatives. And when it comes to design, there are almost always other alternatives.