问题
I want to have all the efficiencies of EnumSet and pass it around without worrying that somebody would modify it.
回答1:
You can get an immutable EnumSet with Google collections (Guava).
Resources :
- Guava home page
- Google-collections bug tracker - immutable enum set convenience constructor
- Google documentation - Sets.immutableEnumSet()
回答2:
What's wrong with Collections.unmodifiableSet()
wrapping an EnumSet
?
True, the original EnumSet
is still mutable, but as long as you discard the original reference, it's as good as immutable inside the wrapper.
edit: OK, since EnumSet
doesn't offer any instance methods over and above the Set
interface, the only reason for not using this solution is that the EnumSet
type is useful for documentation purposes, and you lose that when wrapping it in a Set
. Other than that, EnumSet
behaviour will be preserved.
来源:https://stackoverflow.com/questions/3603810/are-there-plans-for-immutableenumset-in-java-7