Java enums mutability usecases and possibilities?

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.


In response to Alex D's answer and comment, I am taking his suggestion of posting a possible use case. Let's take the old standard enum example of planets from which gravity, etc can be calculated. Imagine that you wanted to maintain the number of human colonies on each planet. Yes you could use a EnumMap, but I could see a case where more and more mutable fields could be needed and having either a seperate map for each value or a separate class to hold the mutable values associated with an enum would be counter-intuitive.

As I stated in my comments, in general I believe enums usually are and should be immutable but I feel that stating that there are no use cases is too strong.


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.

Tags:

Java

Enums

Spring