Java Insert Elements to EnumSet
In Java, you can insert elements into an EnumSet using the add()
method, which is inherited from the AbstractCollection
class. The add()
method takes a single argument, which is the Enum value that you want to add to the set. Here is an example of how to insert elements into an EnumSet:
import java.util.EnumSet; public class EnumSetExample { // Define an enum type enum Color { RED, GREEN, BLUE } public static void main(String[] args) { // Creating an EnumSet EnumSet<Color> set = EnumSet.noneOf(Color.class); // Inserting elements into the EnumSet set.add(Color.RED); set.add(Color.GREEN); set.add(Color.BLUE); // Printing the EnumSet System.out.println("EnumSet: " + set); } }
Output:
EnumSet: [RED, GREEN, BLUE]
In the example above, we have created an EnumSet of the Color
enum using the noneOf()
method, which creates an empty EnumSet of the specified enum type. We have then inserted the RED
, GREEN
, and BLUE
elements into the EnumSet using the add()
method. Finally, we have printed the contents of the EnumSet.
Note that you can also create an EnumSet with one or more elements using the of()
method, which takes one or more Enum values as arguments. For example, you can create an EnumSet containing the RED
and GREEN
elements like this:
EnumSet<Color> set = EnumSet.of(Color.RED, Color.GREEN);
You can also create an EnumSet containing all the elements of the specified enum type using the allOf()
method:
EnumSet<Color> set = EnumSet.allOf(Color.class);