3

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?

Juergen
  • 3,489
  • 6
  • 35
  • 59

1 Answers1

8

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));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thx. I need the performance of EnumSets and the immutability. So your second proposal is what I need. – Juergen Nov 20 '15 at 07:25
  • 1
    @juxeii: Note that you don't have an `EnumSet` there - just an `ImmutableSet`. If you need an `EnumSet` you'll need a different approach - I'm editing my answer. – Jon Skeet Nov 20 '15 at 07:31