开发者

Combining Java EnumSets

If I have an Enum, I can create an EnumSet using the handy EnumSet class

enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
EnumSet<Suit> reds = EnumSet.of(Suit.HEARTS, Suit.DIAMONDS);
EnumSet<Suit> blacks = EnumSet.of(Suit.CLUBS, Suit.SPADES);

Give two EnumSets, how can I create a new EnumSet which开发者_开发技巧 contains the union of both of those sets?

EnumSet<Suit> redAndBlack = ?


An EnumSet is also a collection, so you can use many of the Collection API calls as well, such as addAll.

EnumSet<Suit> redAndBlack = EnumSet.copyOf(reds);
redAndBlack.addAll(blacks);


In this case, you could also use

EnumSet<Suit> redAndBlack = EnumSet.allOf(Suit.class)


Here's the answer extracted into a generic that you can use with any two EnumSet<T>'s to merge them.

private <T extends Enum<T>> EnumSet<T> mergeEnumSet(EnumSet<T> a, EnumSet<T> b) {
    final EnumSet<T> union = EnumSet.copyOf(a);
    union.addAll(b);
    return union;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜