简体   繁体   中英

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM