As far as I understood it would be much easier and clearler to use EnumSet
and that the Set
was specifically designed for using with Enumerators. My question is whether we should consider to use the EnumSet
every time we need to maintain some collection of enumerators. For instance, I have he following enum:
public enum ReportColumns{
ID,
NAME,
CURRENCY
//It may contain much more enumerators than I mentioned here
public int getMaintenanceValue(){
//impl
}
}
And I need to use some collection ofthe enum in the method:
public void persist(Collection<ReportColumns> cols){
List<Integer> ints = new LinkedList<>();
for(ReportColumn c: cols){
ints.add(c.getMaintenanceValue());
}
//do some persistance-related operations
}
so, if I don't care about if the collection is ordered or not should I use EnumSet<E>
every time to improve performance?
As a rule of thumb, whenever you create a collection of enums and don't care about their order, you should create an EnumSet
. As you mentioned, it would give you a slight increase in performance (in fact, most static code analysis tools I know actually warn about not using it).
For a method declaration though, I wouldn't. As another rule of thumb, methods should use the "highest" type possible that still makes sense. The public contract of this method should be "give me a bunch of enums, and I'll persist them". The method shouldn't care what collection is passed, so it makes no sense forcing the parameter type to be an EnumSet
. If the concrete type you pass is indeed an EnumSet
you'll get all the performance benefits anyway.