Java program to create an EnumSet collection from all elements of an enum

Given an enum, we have to create an EnumSet collection from it.
Submitted by Nidhi, on May 27, 2022

Problem Solution:

In this program, we will create an Enum for COLORS constants. Then we will create an EnumSet collection from all elements of an enum using the allOf() method.

Program/Source Code:

The source code to create an EnumSet collection from all elements of an enum is given below. The given program is compiled and executed successfully.

// Java program to create an EnumSet collection 
// from all elements of an enum

import java.util.*;

//Enum for color constants
enum COLORS {
  RED,
  GREEN,
  BLUE,
  BLACK,
  WHITE
};

public class Main {
  public static void main(String[] args) {
    EnumSet < COLORS > enumSet;

    //Adding elements to EnumSet.
    enumSet = EnumSet.allOf(COLORS.class);

    System.out.println("EnumSet is: " + enumSet);
  }
}

Output:

EnumSet is: [RED, GREEN, BLUE, BLACK, WHITE]

Explanation:

The Main class contains a main() method. The main() method is the entry point for the program. And, created a reference of EnumSet collection and initialized it with all elements of COLORS elements using the allOf() method and printed the result.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.