Skip to content

Instantly share code, notes, and snippets.

@busti
Created May 18, 2016 19:34
Show Gist options
  • Save busti/0defd1249bb7d1c91c029e7e6b476fb5 to your computer and use it in GitHub Desktop.
Save busti/0defd1249bb7d1c91c029e7e6b476fb5 to your computer and use it in GitHub Desktop.
Less Crappy runtime Enum
class EnumValues {
private final Set<String> values;
public EnumValues(String[] vals) {
values = new TreeSet<String>();
values.addAll(vals);
}
public boolean isAllowed(String val) {
return values.contains(val);
}
}
class EnumObject() {
private String value;
private final EnumValues values;
public EnumObject(EnumValues vals) {
values = vals;
value = vals.iterator().next();
}
public boolean setValue(String val) {
if (values.isAllowed(val)) {
value = val;
return true;
}
return false;
}
public String getValue() {
return value;
}
}
public stativ void main(String[] args) {
EnumValues e1 = new EnumValues(new String[] {"1A", "2A", "3A"});
EnumValues e2 = new EnumValues(new String[] {"1B", "2B", "3B"});
EnumObject o1 = new EnumObject(e1);
EnumObject o2 = new EnumObject(e2);
System.out.println(o1.setValue("1A")); //true
System.out.println(o1.setValue("2B")); //false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment