EnumSet from array, shortest variant? EnumSet from array, shortest variant? arrays arrays

EnumSet from array, shortest variant?


Just an alternative. Same amount of code, except no need converting to list, using EnumSet.of() :

EnumSet<Options> temp = options.length > 0 ?                         EnumSet.of(options[0], options) :                         EnumSet.noneOf(Options.class);

No worries that first element is repeated(it won't be duplicated in a set anyway), no performance gain or penalties as well.


This is two lines, but slightly less complex:

EnumSet<Options> temp = EnumSet.noneOf(Options.class); // make an empty enumsettemp.addAll(Arrays.asList(options)); // add varargs to it

I don't consider this worse than any other kind of variable declaration for a class which doesn't have the constructor you want:

    SomeClass variable = new SomeClass(); // make an empty object    variable.addStuff(stuff); // add stuff to it


Guava has factory methods for these kinds of situations:It still needs the call to Arrays.asList but at least it's readable.

import com.google.common.collect.Sets;EnumSet<Options> temp = Sets.newEnumSet(Arrays.asList(options), Options.class);