I would like to reference an array with an enum type. This is a pretty standard thing in C++ (my origin), however I’m unsure if this is possible/desirable in Java.
For example, I would like to have an enum such as:
public enum Resource {
COAL,
IRON
}
Then later I would like to reference like this:
Amount[COAL] // The amount of coal
Price[IRON] // The price of iron
I don’t want to make Amount and Price fields of Resource as I would like a list of objects (orders for resources) grouped by the resource type. Manually assigning an int to each type of Resource is no better than public static int final BLAH I feel, nothing gained.
In essence, I’m looking for the enum of C++ which tags things. I realise that this could be the ‘wrong’ way of doing things in Java, so feel free to point me in the direction of the correct Java ethos.
In C++, an enum is effectively an alias for an integer. In Java, they’re “proper” objects – which is why you can’t use them as an array reference.
If you want to look up the value in your array that’s associated with a particular enum object – that sounds like a Map to me! How about replacing those arrays with an
EnumMap<Resource, Double>?The EnumMap class is optimised for use with enum keys, such that it does end up using an array keyed on the enums’ ordinal (integer) value behind the scenes. So it’s much faster than a general-purpose hashmap, and you get the speed of an array-based solution with the semantic expressiveness of a
Map– it’s the best of both worlds.