Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
933 views
Welcome To Ask or Share your Answers For Others

1 Answer

One possible usecase would be lazy initialization (calculate some field values when they are first used, if often they are not used at all), or a "normal" mutable singleton object (like a registry or such).

In most cases, though, enum objects should be immutable, and their fields be final.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...