Java EnumSet Example and Efficiency
EnumSet is one of the specialized Set interface implementation for use with enum types which was introduced in Java 1.5. Many don’t know the purpose or unware of this implementation and end up in storing Enum data in to common collection classes like ArrayList and HashSet.
EnumSet example
package com.sneppets.corejava.collections; import java.util.EnumSet; import java.util.Iterator; import java.util.Set; /** * Program to demonstrate the use of EnumSet * @author sneppets.com */ public class EnumSetExample { enum days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATRUDAY } public static void main(String[] args) { Set<days> set1 = EnumSet.of(days.THURSDAY, days.FRIDAY); Iterator<days> itr = set1.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } Set<days> set2 = EnumSet.allOf(days.class); System.out.println("All of days: " + set2); Set<days> set3 = EnumSet.noneOf(days.class); System.out.println("None of days: " + set3); } }
Output
THURSDAY FRIDAY All of days: [SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATRUDAY] None of days: []
Note:
You cannot insert Null elements in to EnumSet. If you still try to insert, then you end up with NullPointerException.
EnumSet is not Synchronized
Like many other collections, it is not synchronized. In order to prevent accidental unsynchronized access by threads, it should be synchronized externally like the following
Set<days> s = Collections.synchronizedSet(EnumSet.noneOf(days.class));
Time Complexity
Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class is good.
All the basic operations execute in constant time O(1). Though not guaranteed they are much faster when compared to HashSet counterparts. Even when you perform bulk operations it performs better and operations execute in constant time.
Related Posts
- Java Set Interface, Implementations and Examples
- Collection Interface and Examples
- Collection(s) and Collections Framework in Java