I\'m not too experienced with Java yet, and I\'m hoping someone can steer me in the right direction because right now I feel like I\'m just beating my head against a wall...
You're probably better off using a Map rather than a List, you can use the enum as the key and get the values out.
Map<YourEnumType,ValueType> map = new HashMap<YourEnumType,ValueType>();
@Tom's recommendation to use Map
is the preferred approach. Here's a trivial example that constructs such a Map
for use by a static lookup()
method.
private enum Season {
WINTER, SPRING, SUMMER, FALL;
private static Map<String, Season> map = new HashMap<String, Season>();
static {
for (Season s : Season.values()) {
map.put(s.name(), s);
}
}
public static Season lookup(String name) {
return map.get(name);
}
}
Note that every enum
type has two implicitly declared static methods:
public static E[] values();
public static E valueOf(String name);
The values()
method returns an array that is handy for constructing the Map
. Alternatively, the array may be searched directly. The methods are implicit; they will appear in the javadoc of your enum
when it is generated.
Addendum: As suggested by @Bert F, an EnumMap may be advantageous. See Effective Java Second Edition, Item 33: Use EnumMap instead of ordinal indexing, for a compelling example of using EnumMap to associate enum
s.