[Tiny] The Least Known Set in Java: EnumSet

Petr Filaretov - May 31 '23 - - Dev Community

Have you ever used Java standard class EnumSet in real-life applications? Me neither. Nevertheless, it can be useful in some cases.

EnumSet is an abstract Set which can hold enum values only. And if you are about to store enum values in a Set, you should always use EnumSet because it is usually faster and takes less memory. These benefits are achieved by storing data as a bit vector in one of two EnumSet implementations:

  • long bit vector in RegularEnumSet for enum types with 64 or fewer enum constants,
  • long[] bit vector in JumboEnumSet for enum types with more than 64 elements.

But enough talking, let's see it in action!

Here we have an enum of quotes:

@Getter
@AllArgsConstructor
public enum Quote {
    DONT_PANIC("Don't Panic."),
    THE_ANSWER("42"),
    TOWEL("A towel is about the most massively useful thing an interstellar hitchhiker can have."),
    SO_LONG("So long, and thanks for all the fish."),
    ;

    private final String value;
}
Enter fullscreen mode Exit fullscreen mode

Here is how we can create EnumSet:

EnumSet<Quote> allQuotes = EnumSet.allOf(Quote.class);
EnumSet<Quote> noQuotes = EnumSet.noneOf(Quote.class);
EnumSet<Quote> twoQuotes = EnumSet.of(Quote.DONT_PANIC, Quote.TOWEL);
EnumSet<Quote> threeQuotes = EnumSet.range(Quote.DONT_PANIC, Quote.TOWEL);
EnumSet<Quote> sameThreeQuotes = EnumSet.complementOf(EnumSet.of(Quote.SO_LONG));
Enter fullscreen mode Exit fullscreen mode

allQuotes contains all the enum elements, while noQuotes is empty.

twoQuotes contains two listed elements, while both threeQuotes and sameThreeQuotes contain the set of the first three elements of the Quotes enum.

Now, you can use all the standard operations with these sets, e.g. add, remove, contains, etc.


Dream your code, code your dream.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player