Java EnumSet Class Example

Published May 16, 2022

EnumSets are specialised implementations of the Set interface for use with enum types. They inherit AbstractSet and implement the Set interface. Programming languages use enumerations to represent a set of constants. In an enum type, all possible values are known at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. The constants in an enum type need not be fixed.

EnumSet Methods

To perform various operations, an EnumSet uses various methods:

  • allOf (Class elementType)- In this method, all elements with the specified element type are created into an enum set.

  • noneOf (Class elementType)- By using this method, we can create a set of empty enumerations with a specified element type.

  • copyOf(Collection c)- In this method, an enum set is created that is initialised from the specified collection.

  • of(E e)- this method initialises an enum set by specifying a single element and creating it.

  • range (E from, E to)- The method creates an enum set that contains the range of elements specified.

  • clone()- A copy of a specific set is returned using this method.

 

An Example of  EnumSet class

import java.util.EnumSet;

import java.util.Set;

enum fruitz { 

  BERRIES, KIWI, ORANGE, MANGO 

public class EnumSet_Class_Example {

            public static void main(String[] args) {

                        Set<fruitz> set1 = EnumSet.allOf(fruitz.class); 

                  System.out.println("My Favourite fruits:"+set1); 

                  Set<fruitz> set2 = EnumSet.noneOf(fruitz.class); 

                  System.out.println("My Worst Fruits:"+set2);

            }

}

 

Output:

My Favourite fruits:[BERRIES, KIWI, ORANGE, MANGO]

My Worst Fruits:[]

 

Keywords: The Java EnumSet , Java Collections, Java

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

93 Views