EnumSet In Java

enumset in java

What Is EnumSet ?

An unique Set implementation designed for enum types. An enum set’s elements must all originate from the same enum type, which must be provided either explicitly or implicitly when the set is constructed. Internally, enum sets are represented as bit vectors. EnumSet in java makes codes easier 

 

For example:  The four suits in a deck of playing cards could be represented by the enumerators Club, Diamond, Heart, and Spade, which are members of the enumerated type Suit.

Let’s see the Hierarchy of EnumSet

java.lang.Object
   ↳ java.util.AbstractCollection<E>
        ↳ java.util.AbstractSet<E>
             ↳ java.util.EnumSet<E>

The type of stored elements in this case is E.

EnumSet creation in java

The java.util.EnumSet package must first be imported in order to create an enum set.The enum set does not have public constructors, in contrast to other set implementations. To create an enum set, we have to use the predefined methods.

Syntax:

public abstract class EnumSet<E extends Enum <E>>

Here, the elements are defined by E. The requirement that the elements must be of the specified enum type is enforced by the fact that E must extend Enum.

Java EnumSet Example :

Run
import java.util.EnumSet;

enum Color {
  RED, GREEN, BLUE, YELLOW
}

public class Main {
  public static void main(String[] args) {
    // Create an EnumSet with all values of Color
    EnumSet allColors = EnumSet.allOf(Color.class);
    System.out.println("All colors: " + allColors);

    // Create an empty EnumSet
    EnumSet noColors = EnumSet.noneOf(Color.class);
    System.out.println("No colors: " + noColors);

    // Create an EnumSet with specific values
    EnumSet someColors = EnumSet.of(Color.RED, Color.GREEN);
    System.out.println("Some colors: " + someColors);

    // Add an element to the EnumSet
    someColors.add(Color.BLUE);
    System.out.println("After adding blue: " + someColors);

    // Remove an element from the EnumSet
    someColors.remove(Color.GREEN);
    System.out.println("After removing green: " + someColors);

    // Check if the EnumSet contains a specific value
    boolean hasRed = someColors.contains(Color.RED);
    System.out.println("Has red: " + hasRed);
  }
}

Output :

All colors: [RED, GREEN, BLUE, YELLOW]
No colors: []
Some colors: [RED, GREEN]
After adding blue: [RED, GREEN, BLUE]
After removing green: [RED, BLUE]
Has red: true

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription