alex alex - 1 year ago 59
Java Question

Best way to store data that will be needed every session, but will never change

I have a list of keys and corresponding values with about 150 entries. I have a method that will access it multiple times per session, but will never edit it. It will remained unchanged from session to session. I figure because I want to quickly access the values, I would use a hashmap, but I am not sure how to store it for the long term. What the best way of storing it, and then accessing it at the beginning of my program. Thanks!

Answer Source

If it's actually never going to change, you may as well just store it in a static initialization class: public static final. If we assume it's never going to change, then there's no reason to make it easy to change through other techniques such as loading from a file or a database.

It's up to you whether you store it as a HashMap with 150 entries or a 150 fields in a class. I think it depends on how you want to access the data. If you store it as a HashMap, then you'll likely be accessing the values on a String key, e.g. Constants.getData(""). If you store it as 150 fields then just access the fields directly, e.g. Constants.MAX_SEARCH_RESULTS.

As for performance, with 150 entries you have nothing to worry about unless your data is large. People routinely use HashMaps for thousands or millions of entries.

As for when it will be initialized, static fields in Java are initialized only once when the application starts. For 150 entries this should take less than a millisecond (ballpark estimate).

See also