EnumSet
extends
AbstractSet
and implements
Set Interface In Java.
EnumSet
quickly turns any
Enum
elements into a Set. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.
Enum
sets are represented internally as bit vectors.
Null
elements are not permitted. Attempts to insert a null element will throw
NullPointerException
. Attempts to test for the presence of a
null
element or to remove one will, however, function properly.
EnumSet
is not synchronized. If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally.
Declartion of EnumSet :
public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>
implements Cloneable, Serializable
Note : EnumSet defines no constructors.
Methods of EnumSet :
EnumSetDemo
import java.util.*;
class EnumSetDemo
{
enum Weekdays
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
}
public static void main(String[] args)
{
EnumSet set = null; // LINE A
System.out.println(set);
set = EnumSet.of(Weekdays.Monday); // LINE B
System.out.println("set when added monday : " + set);
set = EnumSet.of(Weekdays.Tuesday); // LINE C
System.out.println("set when added tuesday : " + set);
EnumSet weekends = EnumSet.of(Weekdays.Saturday, Weekdays.Sunday); // LINE D
System.out.println("weekends : " + weekends);
EnumSet otherweekdays = EnumSet.complementOf(weekends); // LINE E
System.out.println("Otherdays : " + otherweekdays);
set = EnumSet.allOf(Weekdays.class); // LINE F
EnumSet setCopy = EnumSet.copyOf(set); // LINE G
System.out.println("setCopy elements : " + setCopy);
}
}
OUTPUTnull
set when added monday : [Monday]
set when added tuesday : [Tuesday]
weekends : [Saturday, Sunday]
Otherdays : [Monday, Tuesday, Wednesday, Thursday, Friday]
setCopy elements : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
DESCRIPTIONIn the above program we demonstrated how EnumSet
works. At LINE A
we created a null EnumSet
and displayed it. At LINE B
we added Monday
to set using Of
method and displayed. At LINE C
we added Tuesday
to set using the same Of
method which replaced Monday
in the set. At LINE D
we created weekends
a EnumSet
and added Saturday
, Sunday
and displayed it. At LINE E
we created otherweekdays
which don't have the weekends using complementOf
method and then added all the elements in the enum
Weekdays
to set using allOf method
at LINE F
and created a copy of set
as setCopy
using copyOf
method at LINE G
and displayed it.
THINGS TO TRY
- Add another Birthday to set using add method. Use the below sample code
set.add("Birthday");
The above code throws java.lang.ClassCastException: since the elements in the EnumSet must come from a single enum type.