×

Java Programs

Java Practice

Java program to create an EnumSet collection from an existing EnumSet collection

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

Problem statement

In this program, we will create an Enum for COLORS constants. Then we will create an EnumSet and initialize using the allOf() method. After that, we will create a new EnumSet collection from the existing EnumSet using the copyOf() method.

Java program to create an EnumSet collection from an existing EnumSet collection

The source code to create the EnumSet collection from an existing EnumSet collection is given below. The given program is compiled and executed successfully.

// Java program to create an EnumSet collection from 
// an existing 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;

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

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

    EnumSet < COLORS > newSet = EnumSet.copyOf(enumSet);

    System.out.println("The new EnumSet is: " + newSet);
  }
}

Output

EnumSet is: [RED, GREEN, BLUE, BLACK, WHITE]
The new 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 the EnumSet collection and initialized it with elements of COLORS elements using Of() method. After that, we created a new EnumSet newSet from the existing EnumSet using the copyOf() method and printed the newSet.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





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