Java program to compare two EnumSet collections

Given two EnumSet collections, we have to compare them.
Submitted by Nidhi, on May 28, 2022

Problem Solution:

In this program, we will create an Enum for COLORS constants. Then we will create 3 EnumSet collections and compare EnumSet collections using the equals() method.

Program/Source Code:

The source code to compare two EnumSet collections is given below. The given program is compiled and executed successfully.

// Java program to compare two 
// EnumSet collections

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 > enumSet1;
    EnumSet < COLORS > enumSet2 = EnumSet.noneOf(COLORS.class);
    EnumSet < COLORS > enumSet3;

    enumSet1 = EnumSet.range(COLORS.GREEN, COLORS.BLACK);
    enumSet3 = EnumSet.range(COLORS.GREEN, COLORS.BLACK);

    if (enumSet1.equals(enumSet2))
      System.out.println("The enumSet1, enumSet2 has similar elements.");
    else
      System.out.println("The enumSet1, enumSet2 has different elements.");

    if (enumSet1.equals(enumSet3))
      System.out.println("The enumSet1, enumSet3 has similar elements.");
    else
      System.out.println("The enumSet1, enumSet3 has different elements.");
  }
}

Output:

The enumSet1, enumSet2 has different elements.
The enumSet1, enumSet3 has similar elements.

Explanation:

The Main class contains a main() method. The main() method is the entry point for the program. And, created 3 EnumSet collections enumSet1, enumSet2, enumSet3. Then we compared EnumSet collections using equals() method and printed appropriate message.

Java EnumSet Programs »





Comments and Discussions!

Load comments ↻





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