How to Use the EnumSet Class - Java Language Basics

Java examples for Language Basics:enum

Description

How to Use the EnumSet Class

Demo Code

import java.util.EnumSet;
enum Day {// w  ww  . j a va  2 s . co m
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class Main {
  public static void main(String[] args) {
    // Get all constants of the Day enum  
    EnumSet<Day> allDays = EnumSet.allOf(Day.class);
    print(allDays, "All days: " );
  
    // Get all constants from MONDAY to FRIDAY of the Day enum  
    EnumSet<Day> weekDays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
    print(weekDays, "Weekdays: ");
    
    EnumSet<Day> weekends = EnumSet.complementOf(weekDays);
    print(weekends, "Weekends: ");    
  }
  
  public static void print(EnumSet<Day> days, String msg) {
    System.out.print(msg);      
    for(Day d : days) {
      System.out.print(d + " ");
    }
    System.out.println();
  }
}

Result


Related Tutorials