It makes sense declaring an EnumSet within a enum with the modifiers static
and final
? Or are redundant?
Example:
public enum Guitar {
STRATOCASTER,
LES_PAUL,
CLASSIC;
private static final EnumSet electrics = EnumSet.of(STRATOCASTER, LES_PAUL);
}
Thank you!
tl;dr
Details
Regarding your code:
private
As written, no need for
private
.If marked
private
no other code would have access to this set. So it would serve no purpose.static
Yes,
static
is appropriate. An enum defines a specific number of named instances of its class. The instantiation happens automatically when the class first loads at runtime. So each enum object is a separate object. No need for each of them to have their own set. The set is unchanging, so just define a single instance of that set by marking itstatic
.This makes the syntax more clear as we do not involve any of the enum objects by name. Example code:
Or:
final
Yes, mark it as
final
if this set will be unchanging during the entire run of this app. Marking asfinal
prevents any other set from being assigned to that field.EnumSet
➠Set
Regarding the first
EnumSet
, make that simplySet
.Generally better to promise a more general superclass or interface rather than lock yourself into a specific concrete class.
electrics
➠ELECTRICS
The name
electrics
should be in all uppercase, if you intend this set to be fixed, unchanging. Constants in Java are named in all uppercase, by convention. So,ELECTRICS
.Plural naming of collection
Good that you named
ELECTRICS
in plural. This name suggests the fact that is a collection rather than a singular enum object.Set.of
for unmodifiable collectionAs for the second
EnumSet
, generally usingEnumSet
is the right choice for handling enum objects. TheEnumSet
class is highly optimized for enums, resulting in very fast performance while using very little memory.But the problem here is that
EnumSet
is mutable. I expect you do not want any errant code to be adding or removing elements from your set.So we want an immutable collection there. Java provides an unmodifiable set via the
Set.of…
methods.Under the covers, those methods are free to use any concrete class they want, and so are free to optimize in the choice of underlying class. So you might end up with an efficient concrete class like
EnumSet
. But that is not paramount, as being immuable trumps performance in this situation.Solution code
So I would write that code as:
Explicitly immutable collections in third-party library
An alternative to using
Set.of
is to add a library to your project that provides immutability as an explicit part of its collection data types. Perhaps Eclipse Collections or Google Guava.As for redundancy, see correct Answer by Live and Let Live.