Given a specific set of strings, what’s the best way to map them to a corresponding set of integers? Say I have a class with a few integer constants that I use internally, but need to take incoming external strings and determine the correct corresponding integer constant they map to.
Here’s a simplified example:
public class Example {
public static final int ITEM_APPLE = 0;
public static final int ITEM_BANANA = 1;
public static final int ITEM_GRAPE = 3;
public void incomingData(String value) {
// Possible values would be "apple", "banana", and "grape" in this case.
}
}
What would the most appropriate approach be to go from that value to its corresponding integer constant? A HashMap? Or is ther any way to define these mappings in a static member? Another idea?
I would use a
HashMapas that is closest to what you want to achieve, and therefore a maintainable solution. You can define a static HashMap: