Reputation: 25
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!
Upvotes: 0
Views: 976
Reputation: 2203
It seems like you could hard-code it, e.g. with a map String -> String:
public final class CONST
{
public static final Map<String, String> DATA;
static
{
final Map<String, String> data = new HashMap<>(200);
data.put("key001", "value001");
// ...
data.put("key150", "value150");
DATA = Collections.unmodifiableMap(data);
}
}
This creates the hash table at the time when the class is loaded. If you want to avoid this for some reason you could also use the initialization-on-demand holder idiom
Upvotes: 0
Reputation:
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("max.search.results")
. 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).
Upvotes: 1
Reputation: 331
Never never? In that case, you should consider building a properties (or JSON, etc) file into the jar of your program. You can then use
new Properties(getClass().getResourceAsStream());
from any class at the same package level as the properties file to get the set of key-value pairs.
If in fact it may change occasionally, you might want to think about some sort of external data store as I see has already been mentioned in comments responding to your question.
Upvotes: 1