Monday, March 31, 2014

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementation of Set interface for enumeration type, introduced in Java 1.5 along with enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class few years ago, until I come across one of the finest book for Java programmers, Effective Java. It has an Item on EnumSet, which highlight some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and has pre-defined length, as you can not define a new enum constant at runtime; it allows Java API designer to highly optimize EnumSet. If you look closely, EnumSet also teaches you couple of good design practices to create flexible and maintainable code. For example, EnumSet is an abstract class, and it provides lots of static factory method to create instance of EnumSet e.g. EnumSet.of(...). This method takes advantage of method overloading and variable argument to provide Set of only provided Enum constants. Second good thing is there are two concrete sub-classes of EnumSet e.g. RegularEnumSet and JumboEnumSet, but both are package-private, which means client can not use them directly. Only way to use them is via EnumSet. At runtime, depending upon key size of requested Enum, implementation automatically decide which implementation to use. This provides you immense flexibility and control to rollout a new better version of EnumSet implementation without any change on client side. Anyway, this article is not just about design lessons form this class but more importantly how and when to use EnumSet in Java program. I have shared simple example to demonstrate power of EnumSet, which you will see in next section.
Read more �

No comments:

Post a Comment