Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum to initialize with condition

Tags:

java

enums

Say in some condition I want to initialize my enum Foo with the following values.

private enum Foo {
  BAR1("1"),
  BAR2("2"),
  BAR3("3")
}

In some other cases, I want a different set of values.

private enum Foo {
  BAR1("x"),
  BAR2("y"),
  BAR3("z")
}

Then later in other code, it can use the same enum for processing. How can I do this? Or is there other better approach doing achieve my goal?

like image 874
Stan Avatar asked Oct 05 '15 10:10

Stan


People also ask

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

Can enum be initialized?

C static code analysis: "enum" members other than the first one should not be explicitly initialized unless all members are explicitly initialized.

Can enum be null Java?

An enum can be null. When an enum (like Color in this program) is a field of a class, it is by default set to null. It is not initialized to a value in the enum. It has no value.

How is enum initialized in Java?

Enum constructors can never be invoked in the code — they are always called automatically when an enum is initialized. You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes.


1 Answers

You can have multiple values in the enum initializer, and then logic to pick the appropriate value:

enum Foo {
  BAR1("1", "x"),
  BAR2("2", "y"),
  BAR3("3", "z");

  private final String first, second;

  private Foo(String first, String second) {
    this.first = first; this.second = second;
  }

  String value(boolean condition) {
    return condition ? first : second;
  }
}
like image 86
Andy Turner Avatar answered Oct 18 '22 16:10

Andy Turner