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:
privateAs written, no need for
private.If marked
privateno other code would have access to this set. So it would serve no purpose.staticYes,
staticis 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:
finalYes, mark it as
finalif this set will be unchanging during the entire run of this app. Marking asfinalprevents any other set from being assigned to that field.EnumSet➠SetRegarding 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➠ELECTRICSThe name
electricsshould 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
ELECTRICSin plural. This name suggests the fact that is a collection rather than a singular enum object.Set.offor unmodifiable collectionAs for the second
EnumSet, generally usingEnumSetis the right choice for handling enum objects. TheEnumSetclass is highly optimized for enums, resulting in very fast performance while using very little memory.But the problem here is that
EnumSetis 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.ofis 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.