Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enums mutability usecases and possibilities?

Tags:

java

enums

spring

I don't know if I'm the only one to know that, but the values of an enum are not implicitly final and can be modified.

  enum EnumTest {
    TOTO("TOTO 1"),
    TATA("TATA 2"),
    ;

    private String str;

    private EnumTest(String str) {
      this.str = str;
    }

    @Override
    public String toString() {
      return str;
    }
  }

  public static void main(String[] args) {
    System.out.println(EnumTest.TATA);
    EnumTest.TATA.str = "newVal";
    System.out.println(EnumTest.TATA);
  }

TATA 2
newVal

These values are oftenly initialized at instance creation (TOTO("TOTO 1")) but, except myself, I've never seen anyone using the final keyword for enum variables that should be immutable. That's not the point of the question, just wondering if I'm the only one aware of this.


What I'd like to know is if there was any usecase to create mutable enums?

And I'd also like to know the limits of what we can do with enums (good practice or not). I've not tested it, but maybe an enum can be injected with Spring beans? At least it seems we can annotate each instance (@Deprecated works fine for exemple), and also the methods.

like image 698
Sebastien Lorber Avatar asked Oct 22 '12 16:10

Sebastien Lorber


People also ask

Is enum mutable Java?

The types of all fields of the enum are deeply immutable. For example, use ImmutableList and ImmutableSet instead of List and Set . Types are considered immutable if they are primitives, in a set of types that are built in to Error Prone (e.g. java.

Is enum immutable in Java?

Java enums are tightly immutable, so it makes sense that the enum must return a clone of the array returned by the values() method each time that method is called to ensure that the array associated with the enum is not changed.

Should Java enums be all caps?

Enums are a type and the enum name should start with a capital. Enum members are constants and their text should be all-uppercase.

What is the benefit of enum in Java?

You can declare a function argument, return type, class member or local variable to be a particular Enum type and the compiler will enforce type safety; Enums are basically classes. They can implement interfaces, have behaviour and so on.


1 Answers

While you point out an interesting fact here, as far as I'm concerned, there is no usecase for mutable enum fields. There are many reasons why making use of this language "feature" ("bug"?) would be a bad idea, not least of which is the potential for confusing other developers.

like image 189
Alex D Avatar answered Oct 06 '22 20:10

Alex D