When to use EnumSet in Java
This item advises us to use EnumSet in the place of bit fields, which is part of enum int pattern.
- EnumSet can only be created of a single enum type, which means you can not create EnumSet of Month and DayOfWeek together.
- EnumSet doesn't allow null elements. Attempting to insert null on EnumSet will throwNullPointerException.
- EnumSet is not thread-safe, which means if it needs to be externally synchronized, when multiple threads access it and one of them modifies the collection.
- Iterator of EnumSet is fail-safe and weakly consistent, which means noConcurrentModificationException. Also traversing order of Iterator is defined by natural ordering of Enum, and it may or may not show result of any modification done during iteration.
- EnumSet is a high performance Java Collection. It provides O(1) performance for add(),contains() and next() operations because of array based access. Preferably, useEnumSet over HashSet for storing Enum constants.
No comments:
Post a Comment