Search code examples
javaguavaimmutabilityenumset

Union two ImmutableEnumSets with Guava


I want to union two ImmutableEnumSets from Guava. Here's my try on it:

public final class OurColors {

    public enum Colors {
        RED,
        GREEN,
        BLUE,
        YELLOW,
        PINK,
        BLACK
    }

    public final static ImmutableSet<Colors> myColorSet =
            Sets.immutableEnumSet(Colors.BLUE,
                                  Colors.GREEN);

    public final static ImmutableSet<Colors> yourColorSet =
            Sets.immutableEnumSet(Colors.YELLOW,
                                  Colors.PINK);

    public final static ImmutableSet<Colors> ourColorSet =
            Sets.union(myColorSet, ourColorSet);
}

The field ourColorSet does not compile, it fails with

Type mismatch: cannot convert from Sets.SetView<OurColors.Colors> to
ImmutableSet<OurColors.Colors>

How is the union done correct?


Solution

  • Well, Sets.union returns a Sets.SetView<E>, not an ImmutableSet<E>. So you can do this:

    public final static Sets.SetView<Colors> ourColorSet =
            Sets.union(myColorSet, yourColorSet);
    

    ... which in many cases would be fine, or use Set instead:

    public final static Set<Colors> ourColorSet =
            Sets.union(myColorSet, yourColorSet);
    

    That's still going to be unmodifiable, it just doesn't have the compile-time type of being ImmutableSet<E>. If you really, really need that, you can use immutableCopy():

    public final static ImmutableSet<Colors> ourColorSet =
            Sets.union(myColorSet, yourColorSet).immutableCopy();
    

    ... or to create another enum-aware set:

    public final static ImmutableSet<Colors> ourColorSet =
            Sets.immutableEnumSet(Sets.union(myColorSet, yourColorSet));