EnumSet

In this chapter you will learn:

  1. How to use EnumSet
  2. How to create EnumSet with a list of enum value list

Use EnumSet

EnumSet extends AbstractSet and implements Set. It is specifically for use with keys of an enum type. It is a generic class that has this declaration:

class EnumSet<E extends Enum<E>>

E specifies the elements.

EnumSet defines no constructors. It uses the factory methods to create objects.

The EnumSet class provides a Set implementation that is based on a bitset. Its elements are constants that must come from the same enum. Null elements are not permitted.

The following code use the EnumSet

import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
/*from   ja v  a 2s. c  o m*/
enum Weekday {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class Main {
  public static void main(String[] args) {
    Set<Weekday> daysOff = EnumSet.of(Weekday.SUNDAY, Weekday.MONDAY);
    Iterator<Weekday> iter = daysOff.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());
  }
}

The code above generates the following result.

Create EnumSet with a list of enum value list

import java.util.EnumSet;
import java.util.Iterator;
//from j ava 2  s . c  om
public class Main {
    
    public static void main(String[] args) {
        EnumSet largeSize = EnumSet.of(Size.XL,Size.XXL,Size.XXXL);
        for(Iterator it = largeSize.iterator();it.hasNext();){
            Size size = (Size)it.next();
            System.out.println(size);
        }
    }
}


enum Size {
  S, M, L, XL, XXL, XXXL;

}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use EnumMap Class
  2. How to Map from enum integer
Home » Java Tutorial » Collections
Iterator
ListIterator
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue