简体   繁体   中英

store different enum types in enumSet

I want to store different enum types within one enum.

Is this the right (shortest) way?

public enum MyEnums {
    all(EnumSet.of(Color.red, Shape.round));

    MyEnums(EnumSet<? extends Enum<?>> keys) {
        this.keys = keys;
    }

    private final Set<? extends Enum<?>> keys;

    public Set<? extends Enum<?>> getKeys() {
        return keys;
    }
}

Use a different kind of set. EnumSet is designed to hold enum values of a single kind only :

All of the elements in an enum set must come from a single enum type

The point is that it is very efficient because it stores a bit mask of the present ordinal values - most enums have fewer than 64 values, so all it basically needs in terms of member variables is the Class and a long . (There is a private subclass of EnumSet called something like JumboEnumSet which handles larger enums).

If you have multiple enum types, it can't distinguish values from different enums with the same ordinal.

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