Java.util.EnumSet.of() Method

Advertisements


Description

The java.util.EnumSet.of(E first, E... rest) method creates an enum set initially containing the specified elements. This factory, whose parameter list uses the varargs feature, may be used to create an enum set initially containing an arbitrary number of elements, but it is likely to run slower than the overloadings that do not use varargs.

Declaration

Following is the declaration for java.util.EnumSet.of() method

public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest)

Parameters

  • first -- an element that the set is to contain initially.

  • rest -- the remaining elements the set is to contain initially.

Return Value

This method returns an enum set initially containing the specified elements.

Exception

  • NullPointerException-- if e is null

Example

The following example shows the usage of java.util.EnumSet.Of() method.

/*This example is using a method called main2
to simulate calling the main method using args
from a command line.*/

package com.tutorialspoint;

import java.util.*;

public class EnumSetDemo {

   // create an enum
   public enum Numbers {

      ONE, TWO, THREE, FOUR, FIVE
   };

   public static void main(String[] args) {

      // create a fake list that will be used like args
      Numbers[] list = {Numbers.ONE, Numbers.THREE, Numbers.FOUR, Numbers.FIVE};

      // call the fake main
      main2(list);

   }

   // This is a fake main. This is used as an example
   public static void main2(Numbers[] fakeargs) {

      // create a set
      EnumSet<Numbers> set;

      // add first element and the rest of fakeargs
      set = EnumSet.of(Numbers.ONE, fakeargs);

      // print the set
      System.out.println("Set:" + set);

   }
}

Let us compile and run the above program, this will produce the following result:

Set:[ONE, THREE, FOUR, FIVE]



Advertisements
Advertisements