More on Enums

Please visit Enums blog before venturing further into this article.

Singleton Implementation 

Enums are by default thread-safe and provide an easy and simple implementation of Singleton Design pattern.

Screen Shot 2020-01-31 at 2.35.47 PM

EnumSet

An EnumSet is a specialized Set collection to work with enum types.

EnumSet should always be preferred over any other Set implementation when we are storing enum values.

The EnumSet is an abstract class that has two implementations called RegularEnumSet and JumboEnumSet, one of which is chosen depending on the number of constants in the enum at the time of instantiation.

Few properties of EnumSet

  • It can contain only enum values and all the values have to belong to the same enum type.
  • It doesn’t allow to add null values
  • It’s not thread-safe
  • The elements are stored following the order in which they are declared in the enum
  • It uses a fail-safe iterator that works on a copy, so it won’t throw a ConcurrentModificationException if the collection is modified when iterating over it.

Benefits from Using an EnumSet

  • All the methods in an EnumSet are implemented using arithmetic bitwise operations. These computations are very fast and are executed in a constant time.
  • It’s a high performance set implementation, much faster than HashSet.Unlike HashSet, there’s no need to compute the hashcode to find the right bucket.
  • It uses less memory, with all the benefits that it brings.

E16

Output

O16

EnumMap

EnumMap is optimized Map implementation exclusively for enum keys . All keys used in EnumMap must be from same Enum type.

Few properties of EnumMap

  • EnumMap is implemented using Arrays and common operations result in constant time.
  • Since all possible keys are known in advance, a quicker hash computation is possible. So it is much faster as compared to HashMap.
  • It is important to note that null keys are not permitted. However, null values are allowed.
  • Also, note that EnumMap is not synchronized.
  • EnumMap is ordered collection and they are maintained in the natural order of their keys( natural order of keys means the order on which enum constant are declared inside enum type )
  • It uses a fail-safe iterator that works on a copy, so it won’t throw a ConcurrentModificationException if the collection is modified when iterating over it.

Screen Shot 2020-01-31 at 3.22.50 PM

Output

Screen Shot 2020-01-31 at 3.22.59 PM

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *