Java program to remove all elements of EnumSet collection

Given an EnumSet collection, we have to remove all elements.
Submitted by Nidhi, on May 29, 2022

Problem Solution:

In this program, we will create an Enum for COLORS constants. Then we will create an EnumSet collection and add elements to it. After that, we will remove all elements of the EnumSet collection using the clear() method.

Program/Source Code:

The source code to remove all elements of the EnumSet collection is given below. The given program is compiled and executed successfully.

// Java program to remove all elements of 
// EnumSet collection

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("Elements of enumSet is: " + enumSet);

    enumSet.clear();
    System.out.println("Elements of enumSet is: " + enumSet);
  }
}

Output:

Elements of enumSet is: [RED, GREEN, BLUE]
Elements of enumSet is: []

Explanation:

Here, we created an EnumSet collection and add elements to it. Then we removed all elements from EnumSet Collection using the clear() method and printed the updated EnumSet collection.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





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