Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for ENUM

Tags:

java

enums

I want to define a default value for an Enum class. The idea of my enum is to define a few specific String values and tie them to enumerations. However, if a user provide an String that I am not expecting, I want the enum to reflect an invalid state. Consider

  public class EnumDemo {

  public enum Food {
    HAMBURGER("h"), FRIES("f"), HOTDOG("d"), ARTICHOKE("a"), INVALID("invalid");

    Food(String code) {
      this.code = code;
    }

    private final String code;

    public String getCode() {
      return code;
    }

    public static Food fromString(String value) {

      return Arrays.stream(Food.values()).filter(s -> s.code.equalsIgnoreCase(value)).findFirst()
          .orElse(Food.INVALID);
    }
  }

  public static void main(String[] args) {
    Food f1 = Food.fromString("h");
    System.out.println(f1 + " " + f1.getCode());
    f1 = Food.fromString("x");
    System.out.println(f1 + " " + f1.getCode());
  }

}

this prints out

HAMBURGER h
INVALID invalid

The problem here is that I am defining the string for the code. invalid is hardcoded as per

INVALID("invalid")

Is it possible to make this a variable? So that I can keep track of what the invalid input was? I tried

INVALID(String x)

but obviously got a syntax exception. Would it just be better not to use an enum?

Lastly, the reason I want to keep track of invalid inputs is that in the future, I want the flexibility to change the enum depending on the users.

like image 730
AbtPst Avatar asked Sep 07 '26 14:09

AbtPst


1 Answers

You could create a wrapper to stash the original input:

public class FoodInput {

    private final Food food;
    private final String input;

    public FoodInput(String input) {
        this.food = Food.fromString(input);
        this.input = input;
    }

    public Food getFood() {
        return food;
    }

    public String getInput() {
        return input;
    }
}
like image 161
Darren Avatar answered Sep 10 '26 04:09

Darren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!