'Where is the best place to define a big list of hard coded key-value pairs in Java?

For context, I'm doing some kind of game in Java where there are hundreds of items. And other than their unique name (which serves as id aswell) they also have a numeric price.

Where do I store all those hard-coded price values for each item? Do I make a constants class for all of them? And if so how would I search for the specific price of the item "shovel"? Since there are no dictionaries in Java like there are in Python for example. Or do I need to use a database even though they will probably never change?



Solution 1:[1]

Java does have "dictionaries", except it's called java.util.Map (with implementations like HashMap or TreeMap). There is also java.util.Properties, which is probably what I would use here in combination with a resource.

try (InputStream inputStream = myClass.getResourceAsStream("my.properties")) {
    Properties properties = new Properties();
    properties.load(inputStream);
    // now you can use properties.getProperty("key")
}

The properties file itself (my.properties) is then located in the same location as the class file. Its content is a list of key-value pairs:

key1 = value1
key2 = value2
# for comments

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Spoor