Home »
Java »
Java Programs
Java program to add elements to EnumSet collection using add() method
Given an EnumSet collection, we have to add elements using add() method.
Submitted by Nidhi, on May 28, 2022
Problem statement
In this program, we will create an Enum for COLORS constants. Then we will create an EnumSet collection and add elements using add() method.
Java program to add elements to EnumSet collection using add() method
The source code to add elements to the EnumSet collection using add() method is given below. The given program is compiled and executed successfully.
// Java program to add elements to EnumSet
// using add() method
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 = EnumSet.noneOf(COLORS.class);
enumSet.add(COLORS.RED);
enumSet.add(COLORS.GREEN);
enumSet.add(COLORS.BLUE);
System.out.println("enumSet elements: " + enumSet);
}
}
Output
enumSet elements: [RED, GREEN, BLUE]
Explanation
The Main class contains a main() method. The main() method is the entry point for the program. And, created an EnumSet collection and add elements to it using add() method. Then we printed the elements.
Java EnumSet Programs »