This is the same problem that Enterprise Java developers face when persisting an enum to a database. The problem with the existing answers is that they are fragile and not refactoring-friendly. Here's why (with an alternative at the bottom.)
Using an enum's toString()
and valueOf()
methods means that an enum value can't be renamed. Suppose I have a VehicleType
enum with values CAR
and TRUCK
. If I store the string "TRUCK" as a preference value and then rename VehicleType.TRUCK
to VehicleType.PICKUP_TRUCK
in the next version of my app, the stored string no longer makes sense and valueOf()
will throw an IllegalArgumentException
.
Using a value's ordinal means that the enum values can't be re-ordered or your stored values will no longer match up. This scenario is arguably worse because your app will continue to run but may behave in unexpected ways, making the issue difficult to track down once it's finally noticed and likely impossible to correct. The same is true for adding a new value anywhere but the end. If I added a new MOTORCYCLE
value at the top, a CAR
stored as its ordinal (0) in the previous version of the app would come back as MOTORCYCLE
after updating, and a TRUCK
(ordinal 1) would become a CAR
.
The alternative I use is to add a final
field to the enum and use its value, like so:
public enum VehicleType {
CAR("C"),
TRUCK("T");
private final String code;
private static final Map<String,VehicleType> valuesByCode;
static {
valuesByCode = new HashMap<>(values().length);
for(VehicleType value : values()) {
valuesByCode.put(value.code, value);
}
}
VehicleType(String code) {
this.code = code;
}
public static VehicleType lookupByCode(String code) {
return valuesByCode.get(code);
}
public String getCode() {
return code;
}
}
Store a value using something like preferences.putString("vehicle_type", vehicleType.getCode())
and retrieve it using something like vehicleType = VehicleType.lookupByCode(preferences.getString("vehicle_type", null))
.
This approach requires a little extra code but in my opinion, it's the most robust solution.